0

I am calling two requests with axios.all() on mounted() and I can not assign the response data to my Vue data. I have included some console.log() in order to understand what is going on.

app = new Vue({
    data: {
        countries: [],
        cities: [],
    },
    methods: {
        getCountries() {
            return axios({
                method: 'get',
                url: '/utils/countries/',
            })
        },
        getCities() {
            return axios({
                method: 'get',
                url: '/utils/cities/',
            })
        }
    },
    mounted() {
        console.log('1 ' + this.cities)
        axios.all([this.getCountries(), this.getCities()])
        .then(axios.spread(function (countries, cities) {
            this.countries = countries.data;
            this.cities = cities.data;
            console.log('2 ' + this.cities)
        }))
        .catch(error => console.log(error));
        console.log('3 ' + this.cities)
    }
});

Ouput :

1
3
2 [object Object]...

My call is successful but this.citiesand this.countries remains empty. How can I pass them my response data?

Aurélien
  • 1,617
  • 1
  • 21
  • 33
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Styx Jul 07 '19 at 10:15

1 Answers1

2

The this keyword inside your Axios callback probably refers to the lexical context of its own function. Because of this, you're assigning to a cities and countries property on the wrong object. Which is why those properties remain empty on your Vue component.

By using an arrow function, this will be bound to the enclosing lexical context, which is in this case, your Vue component.

Try this:

.then(axios.spread((countries, cities) => {
    this.countries = countries.data;
    this.cities = cities.data;
}))
NvdB31
  • 302
  • 1
  • 3
  • 13