0

I am retrieving data from the Vuex Store. I first of all want to check of the array is present in the Vuex Store, after that I want to check if the noProducts object at index 0 is not present.

The reason for this is that tweakwiseSortedProducts is used for both products and a no Products boolean to react to in the front-end

tweakwiseHasProducts () {
  if (this.$store.state.tweakwise?.tweakwiseSortedProducts) {
    return (
      this.$store.state.tweakwise.tweakwiseSortedProducts[0].noProducts ===
      false
    );
  }
  return false;
},

My front-end currently, often, returns:

this.$store.state.tweakwise.tweakwiseSortedProducts[0] is undefined

In the console.

0

2 Answers 2

2

This happens because tweakwiseSortedProducts is not undified but an empty list. You can try:

tweakwiseHasProducts () {
  if (this.$store.state.tweakwise?.tweakwiseSortedProducts?.length !== 0) {
    return (
      this.$store.state.tweakwise.tweakwiseSortedProducts[0].noProducts ===
      false
    );
  }
  return false;
},

or just:

tweakwiseHasProducts () {
  return this.$store.state.tweakwise?.tweakwiseSortedProducts[0]?.noProducts === false;
},

which will be false if any of this elements is undefined, or true if noProducts is really false

Sign up to request clarification or add additional context in comments.

Comments

1

It is recommended to use getter when calling a value in Vuex.
Please refer to the following.

  getters: {
    getTweakwiseSortedProducts: (state: any) => {
      return state.tweakwise?.tweakwiseSortedProducts || [];
    },
  },

tweakwiseHasProducts () {    
  this.$store.getters.getTweakwiseSortedProducts.length ? true : false;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.