0

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);
    },
Antonio Morales
  • 1,044
  • 2
  • 16
  • 35
  • well, maybe this? – Xinchao Jun 21 '22 at 18:23
  • Does this answer your question? [Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable) – gre_gor Jun 21 '22 at 18:42

1 Answers1

1

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

see this

Sombriks
  • 3,370
  • 4
  • 34
  • 54