Search code examples
vue.jsvuex

Make a computed property based on a mapped computed property on vuejs


I need to use the value of the mapped state to generate another computed property.

computed: {
    ...mapState({
      items: (state) => state.items.items,
    }),
    isFood:  this.items.find(
          (item) => item.category == "Food"
        ) !== undefined
  },

when I try to run this, I get the error of Cannot read property 'items' of undefined.


Solution

  • You're trying to call this.items.find at declaration time of isFood - this wouldn't exist yet. Make it a function:

    isFood() {
      return this.items.some((item) => item.category === "Food");
    },
    

    I also changed your function to use some() so that it won't bother looping through the rest of the items array when it finds a food.