Home > front end >  Cannot read properties of undefined (reading) in Vue3
Cannot read properties of undefined (reading) in Vue3

Time:06-22

I am getting this call from the famous ApiPokemon: https://pokeapi.co/api/v2/pokemon?limit=151

Once I have that data I want to pass it through another method (_getPokemonData) to map the complete data for each Pokémon.

However when I create this VueJS method I get this error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '_getPokemonData')

Why can't I call the _getPokemonData method inside the forEach? This is my code:

mounted() {
    this.$http
      .get("https://pokeapi.co/api/v2/pokemon?limit=151")
      .then((response) => {
        //this.pokemons = response.data.results;
        this.pokemons = response.data.results.forEach(function(pokemon){
          this._getPokemonData(pokemon); 
        });
      });

    this.$http
      .get("https://pokeapi.co/api/v2/type/")
      .then((response) => {
        this.types = response.data.results;
      });
  },

  methods: {
    _getPokemonData(pokemon) {
      console.log(pokemon);
    },

CodePudding user response:

switch the function in forEach for a arrow function. by using 'function' you create a new scope which hijacks the 'this' reference.

see this

  • Related