Home > front end >  How to resolve Cannot read properties of undefined error?
How to resolve Cannot read properties of undefined error?

Time:11-06

I have a this warning:

[Vue warn]: Error in render: "TypeError: Cannot read properties of undefined (reading 'nestedArray')"

What is the solution to this? This is my beforeCreate functions:

  beforeCreate() {
    this.$store.dispatch("loadCities").then((response) => {
      this.cities = response;
      this.sortingCities=this.cities.slice(0).sort(function(a,b) {
        return a.row - b.row || a.col-b.col;
      })
     
      this.sortingCities.map(item => {
        if (!this.nestedArray[item.row]) {
          this.nestedArray[item.row] = [];
        }
        this.nestedArray[item.row][item.col] = item;
      });
    });

My data property:

  data() {
    return {
      cities: [],
      selectedCity: null,
      sortingCities:[],
      nestedArray:[],
    };
  },

I use this property:

<img  :src="require(`../images/${this.nestedArray?.[row]?.[col].imageId}.png`)" alt="">

CodePudding user response:

Inside beforeCreate you should not expect any data, methods or computed to be available. This is documented here (vue 3) and here (vue 2).

Move the contents of beforeCreated into mounted.
If you have anything in <template> depending on the fetched data, give it an appropriate v-if (e.g: v-if="nestedArray.length").

CodePudding user response:

if (!this.nestedArray[item.row]) will only work if you have already initialised this.nestedArray. You need to initialise it to an empty array (or perhaps an array of empty arrays, as long as sortingCities). Attempting to look up a property on an object which doesn't exist (and arrays are a type of object in javascript, albeit a special type) will cause an error.

  beforeCreate() {
    this.$store.dispatch("loadCities").then((response) => {
      this.cities = response;
      this.sortingCities=this.cities.slice(0).sort(function(a,b) {
        return a.row - b.row || a.col-b.col;
      })
     
      this.nestedArray = []

      this.sortingCities.map(item => {
        if (!this.nestedArray[item.row]) {
          this.nestedArray[item.row] = [];
        }
        this.nestedArray[item.row][item.col] = item;
      });
    });
  • Related