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
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
}
Why is this happening? How can I avoid this?
2
Answers
Not sure what kind of object
useState
returns but if you need a.value
, it’s aref
(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.
Based on official docs :
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 :