Do not trigger the watch when the store is hydrated
KaliaJS opened this issue · 4 comments
Clear and concise description of the problem
I didn't know if I should put it as a bug or as a new feature. Sorry if this is in the wrong category.
When the data is already persisted, the watch is triggered when the store is loaded. It's not the case with useStorage() from VueUse. Is it possible to change the behavior like VueUse. If the answer is no, is there a reason?
export const useFooStore = defineStore('foo', () => {
const foo = reactive({ bar: '' })
const bar = ref('')
})
watch(() => foo.bar, () => console.log('triggered'))
watch(foo, () => console.log('triggered'))
watch(bar, () => console.log('triggered'))
watch(bar, () => console.log('triggered'), { immediate: false })
// etc.
Even if I put immediate: false
Suggested solution
Copy the VueUse way of doing things with UseStorage. I find it much more logical.
export const useFooStore = defineStore('foo', () => {
const foo = useStorage('foo', {
bar: '',
})
})
watch(() => foo.value.bar, () => console.log('NOT triggered'))
watch(() => foo.value.bar, () => console.log('NOT triggered'), { immediate: false })
watch(() => foo.value.bar, () => console.log('triggered'), { immediate: true })
Alternative
No response
Additional context
No response
Validations
- Follow our Code of Conduct
- Read the Contributing Guide.
- Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
could you give a repo to show the issue?
Yes of course : Codesandbox Repo
ok, now I known why all watcher will be triggered. From the perspective of plugin principles, when a store
is hydrated is after store.$state
is initialized. all watcher is created and then hydration will trigger them. we just give store
the data it saved, and keep its data newest. but we did no reactive things.
The plugin does not interact with pinia internals, and won't initialize state with stored values. It hydrates the pinia store with stored values, therefore it triggers watchers and eventual reactivity.