Skip to content

storeToRefs not working with optional parameters, when not explicitly set to undefined #1335

Closed
@plehnen

Description

@plehnen

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions