Home > OS >  TypeError: Cannot read properties of undefined (reading 'products')
TypeError: Cannot read properties of undefined (reading 'products')

Time:11-14

I am trying to get products, then check if the product pId is in an array, and filter if it is. I get an error when i soft refresh of 'TypeError: Cannot read properties of undefined' (reading 'products'), almost like my 'this.products' isnt populated yet when computed is trying to get the data. Tried adding some if statements to check data is there but no luck.

<script>
export default {
  data() {
    return {
      popular_products: [],
      products: [],
    }
  },

  computed: {
    bestsellers() {
      const keywords = this.popular_products
      let array = []
      for (var index = 0; index < keywords.length; index  ) {
        const keyword = this.products.data.products.product.filter(
          (product) => product.pId == keywords[index].ProductNumber
        )
        array = array.concat(keyword)
      }
      return array
    },
  },

  mounted() {
    axios
      .get(
        'https://myurl/admin/api/collections/get/popularproducts?token=account-9306f9192049d3c442e565f2de5372'
      )
      .then((response) => (this.popular_products = response.data.entries))

    axios
      .get('https://myurl/products.json')
      .then((response) => (this.products = response))
  },
}
</script>

CodePudding user response:

The problem is with this line:

let keyword = this.products.data.products.product.filter(product => product.pId == keywords[index].ProductNumber);

more specific with this read: data.products.

You see, computed property bestsellers is evaluated before your axios calls are finished.

Because of that, Vue can't find products in data because your this.products doesn't have data key.

The best solution would be to change this assignment:

- .then(response => (this.products = response)); // delete this line
  .then(response => (this.products = response.data.products)); // add this line

Update After comment.

if (this.products.product) {
  return this.products.product.filter(...)
} else {
  return []
}
  • Related