Description
Reproduction
https://codesandbox.io/s/pinia-vue-3-demo-forked-fym6d4?file=/src/stores/cart.js
Steps to reproduce the bug
If a state field can be undefined, it is likely that someone (like me) will write the store like this:
export type State = {
optional?: string;
mandatory: string;
};
export const useMyStore = defineStore('myKey', {
state: (): State => ({
mandatory: '',
}),
...
Expected behavior
storeToRefs is working
Actual behavior
storeToRefs is not working.
Only if you pass the whole store, its property "optional" is present and can be used reactivly.
Additional information
I am in the middle of migrating vuex to pinia, and this issue caused me a long time to figure out, why it wasn't working. So maybe it could be added to the documentation, that even optional values needs to be initialized (with undefined
).
I also found another bug, that if the new value is an object (actually a proxy), the value is not shown in the template via storeToRefs
, even when it was initially set to undefined
. I fixed that by adding lodash cloneDeep (i.e. this.myStateValue = cloneDeep(newValue);
. Couldn't reproduce this in a repro outside of my project, so I didn't created a separate ticket - but at least wanted to mention this here.