Yorg Vermeulen
Yorg Vermeulen

Reputation: 216

Can't get value outside of Axios call

I'm hoping you could help me with a problem I'm having with axios.

I'm just trying to get a value outside of my call, but I can't get it to work. It's this little piece of code:

 axios.get('/api/get-user').then(({ data }) => {
            this.user = data;
            console.log(this.user); //returns the correct data
            return this.user;
        });

        console.log(this.user); //returns null

What is going on here? I also tried it with let self = thisbut to no avail. I hope you guys can help me out!

Upvotes: 0

Views: 215

Answers (1)

Cal Irvine
Cal Irvine

Reputation: 1144

This is a problem with async, you are calling console.log before the axios request has finished. This is why we use the .then(res=>{}).

An alternative would be to use async await.

Decorate your parent function with async

const myFunction = async() => {
    const {data} = await axios.get('/api/get-user');
    this.user = data;
    console.log(this.user);
}

See MDN for more info, this link is to examples (which I find most helpful for understanding) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Examples

Upvotes: 7

Related Questions