Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot read properties of undefined (reading) in Vue3

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
    },

>Solution :

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

see this

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading