Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading