Home > Net >  How to destructure an object property from a Pinia getter that returns an object conditionally?
How to destructure an object property from a Pinia getter that returns an object conditionally?

Time:04-30

I got the following Store:

export const useMyStore = defineStore('myStore', {
  state: () => {
    return {
      openTransOnly: false,
      keyword: '',
      openTransStatus: { nextPage: 0, complete: false },
      pastDueTransStatus: { nextPage: 0, complete: false },
    };
  },

  getters: {
    transStatus(state) {
      return state.openTransOnly ? state.openTransStatus : state.pastDueTransStatus;
    },
  },
});

Now let's say I want to convert the "keyword" property above to a Ref. Here's how I did that:

const myStore = useMyStore();
const { keyword: needle } = storeToRefs(myStore);

I also have the following computed property in my component:

const page = computed({
  get: () => myStore.transStatus.nextPage,
  set: (value) => (myStore.transStatus.nextPage = value),
});

which works fine. However, I'd like to know how to use the same "storeToRefs" above to define the "page". I tried this:

const { keyword: needle, transStatus: { nextPage: page } } = storeToRefs(myStore);

But it says "page is undefined". What am I doing wrong? Is this even possible?

CodePudding user response:

As storeToRefs name suggests, it returns refs. transStatus is a ref and doesn't have nextPage property, it is transStatus.value.nextPage. Destructuring nextPage early would result in the loss of reactivity due to the way transStatus works and because the value is scalar.

In case this is a common usage scenario, the store can incorporate page computed. Since store state isn't supposed to be mutated outside a store, page can be coupled with setPage action.

  • Related