N
Nuxt8mo ago
Tumulte

Does useState() a default value when the state key already set ?

The doc is unclear on the topic and my tests show contradictory results. Let's say I call a component multiple times with
//component A

const foo = useState('foo', ()=>{user: null})
foo.value.user = 'toto';
//component A

const foo = useState('foo', ()=>{user: null})
foo.value.user = 'toto';
//component B

const foo = useState('foo', ()=>{user: null})
foo.value.user = 'bar';
//component B

const foo = useState('foo', ()=>{user: null})
foo.value.user = 'bar';
will the second useState() be reset to {user: null} then to {user: 'bar'} or is useState smart enough to know it aleady has a value and to not reinstantiate itself ?
14 Replies
pyplacca
pyplacca8mo ago
The latter If you’re updating states in a test, you’d usually want to await a nextTick
Tumulte
TumulteOP8mo ago
so useState's default for key 'foo' will strictly be set if 'foo' doesn't exist ?
pyplacca
pyplacca8mo ago
Correct
Tumulte
TumulteOP8mo ago
I don't think it's explained in the docs that's a pity but thanks a lot !
Tumulte
TumulteOP8mo ago
it's even more confusing when they suggest to use composable https://nuxt.com/docs/getting-started/state-management#shared-state
Nuxt
State Management · Get Started with Nuxt
Nuxt provides powerful state management libraries and the useState composable to create a reactive and SSR-friendly shared state.
Tumulte
TumulteOP8mo ago
it might imply that it won't work outside a composable but alright, that's all clear now thanks again
pyplacca
pyplacca8mo ago
Alright 👍
Tumulte
TumulteOP8mo ago
if you allow me one very last question : is it bad to use useState in a loop ? where it might be checked a hundred times ?
pyplacca
pyplacca8mo ago
Oh it’s fine It’s just a state. The only difference between that and a ref is that it’s globally accessible
Tumulte
TumulteOP8mo ago
and a third thanks to you sir
pyplacca
pyplacca8mo ago
You’re welcome
Tumulte
TumulteOP8mo ago
or lady or person 🙂
pyplacca
pyplacca8mo ago
😂 She’s a he 🙃
manniL
manniL8mo ago
PR welcome!
Want results from more Discord servers?
Add your server