Doing a Get using Axios (Vue.js)

Asked

Viewed 2,649 times

3

I’m trying to pull up a list of names coming from a json (http://pokeapi.co/api/v2/pokemon) using the Xios but I don’t understand why I get the error

Typeerror: Cannot set Property 'Pokemons' of Undefined

Since my.log console is returning the list correctly, it follows the code of my Vue component:

<template>
  <div class="w-cards">
   <div v-for="pokemon in pokemons" class="card">
    <h1>{{pokemon.name}}</h1>
   </div>
  </div>

<script>

import axios from 'axios'

export default {
  data() {
      return {
         pokemons: {

         },
     }
 },

created: function() {
    this.buscaPokemons();
},

methods: {
    buscaPokemons: function(){
        axios.get('http://pokeapi.co/api/v2/pokemon')
        .then(function(res){
            console.log(res);
            console.log(res.data.results);
            this.pokemons = res.data.results;
        })
        .catch(function(err){
            console.log(err);
        })
    }
  },
}
</script>

1 answer

4


The problem is that this in the context of this callback function is no longer your Vue instance. You can use a Arrow Function:

.then( res => {
    console.log(res);
    console.log(res.data.results);
    this.pokemons = res.data.results;
});

Or save a reference to the Vue instance before:

buscaPokemons: function(){
    var vm = this;
    axios.get('http://pokeapi.co/api/v2/pokemon')
    .then(function(res){
        console.log(res);
        console.log(res.data.results);
        vm.pokemons = res.data.results;
    })
    .catch(function(err){
        console.log(err);
    })
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.