search

Home  >  Q&A  >  body text

How to conditionally destructure an object property from a Pinia getter?

I have the following stores:

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" attribute above into a Ref. This is what I did:

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

I also have the following computed properties in my component:

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

good results. However, I would like to know how to define "pages" using the same "storeToRefs" above. I tried this:

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

But it says "Page is not defined". What did I do wrong? is it possible?

P粉148434742P粉148434742454 days ago786

reply all(1)I'll reply

  • P粉394812277

    P粉3948122772023-11-09 09:55:18

    As the storeToRefs name suggests, it returns a reference. transStatus is a reference and has no nextPage attribute, it is transStatus.value.nextPage. Due to the way transStatus works and the fact that the value is a scalar, premature destructuring of nextPage can result in a loss of reactivity.

    If this is a common usage scenario, the store can incorporate page calculations. Since the store state should not change outside the store, page can be used in conjunction with the setPage action.

    reply
    0
  • Cancelreply