Making a Get using Axios (Vue.js)

3

I'm trying to pull a list of names from a json ( link ) using the axes however I do not understand why I get the error

TypeError: Can not set property 'pokemons' of undefined

Since my console.log 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>
    
asked by anonymous 09.08.2017 / 03:54

1 answer

4

The problem is that this in the context of this callback function is no longer your Vue instance. You can use an 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);
    })
}
    
09.08.2017 / 03:58