skip to Main Content

Please see this minimum example, if I use useState , normally, I can write something like this:

<script setup>
const num = useState('num', () => 1);
</script>

<template>
  <div>
    {{ num }}
  </div>

  <div>
    {{ typeof num }}
  </div>

  <div>
    {{ JSON.stringify(num) }}
  </div>
</template>

And the result is what I expected:

1
number
1

enter image description here

However, when I move the useState into composables, everything changed, like this:

export const useNum = () => {
  const num = useState('num', () => 1);

  return {
    num,
  };
};
<script setup>
const numStore = useNum();
</script>

<template>
  <div>
    {{ numStore.num }}
  </div>

  <div>
    {{ typeof numStore.num }}
  </div>

  <pre>
    {{ JSON.stringify(numStore.num, null, 2) }}
  </pre>
</template>

the result is super weird:

1
object
    {
  "_object": {
    "$s__nuxt_devtools__": {
      "timeSsrStart": 1719387436211
    },
    "$snum": 1
  },
  "_key": "$snum",
  "__v_isRef": true
}
  

enter image description here

enter image description here

Why is this happening? How can I avoid this?

2

Answers


  1. Not sure what kind of object useState returns but if you need a .value, it’s a ref (not sure why it is not in the first context).
    You can also use toValue if you wish to not get bored trying to find out exactly what is inside of your variable.

    As for the rest (pinia topic), careful with the singleton pattern in an SSR context as written in the docs yes.

    Login or Signup to reply.
  2. Based on official docs :

    Ref unwrapping in templates only applies if the ref is a top-level property in the template render context.

    By unwrapping we mean not using .value

    So try to destruct the return value of your composable to make the ref as top-level property or use the .value in template :

    <script setup>
    const { num } = useNum();
    </script>
    
    <template>
      <div>
        {{ num }}
      </div>
    
      <div>
        {{ typeof num }}
      </div>
    
      <pre>
        {{ JSON.stringify(num, null, 2) }}
      </pre>
    </template>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search