Axios Prints Value On Console But Returns Undefined
I have quite an issue for some time and is getting on my nerves and it doesn't make sense. I have used axios on my react frontend and it works perfect when assigning the get value
Solution 1:
You can't return an ajax response because it's asynchronous. You should wrap your function into a promise or pass a callback to login
UPDATE: As @Thilo said in the comments, async/await
would be another option, but it will let you set the response to data tho ...
1. Wrap into a promise
login = () =>newPromise((resolve, reject)=>{
axios.get('https://myaddress/authenticate')
.then(response => {
resolve(response)
})
.catch(error => {
reject(error)
});
});
// Usage examplelogin()
.then(response =>{
console.log(response)
})
.catch(error => {
console.log(error)
})
2. Pass a callback
login = (callback) => {
axios.get('https://myaddress/authenticate')
.then(response => {
callback(null,response)
})
.catch(error => {
callback(error,null)
});
};
// Usage examplelogin((err, response)=>{
if( err ){
throw err;
}
console.log(response);
})
3. Async/Await
login = async () => {
// You can use 'await' only in a function marked with 'async'// You can set the response as value to 'data' by waiting for the promise to get resolvedlet data = await axios.get('https://myaddress/authenticate');
// now you can use a "synchronous" data, only in the 'login' function ...console.log('eee', data);
return data; // don't let this trick you, it's not the data value, it's a promise
};
// Outside usageconsole.log( login() ); // this is pending promise
Solution 2:
In ES7/ES8 you can do async/await like a boss:
login = () => {
returnnewPromise((resolve, reject) => {
axios.get('https://myaddress/authenticate')
.then(response => {
resolve(response)
})
.catch(error => {
console.error('auth.error', error);
reject(error)
});
});
};
asyncfunctiongetData() {
try{
const data = awaitlogin()
} catch(error){
// handle error
}
return data;
}
getData()
.then((data) =>console.log(data));
Post a Comment for "Axios Prints Value On Console But Returns Undefined"