Using axios in React where I am calling an endpoint to fetch JWT token as follows
fetchJwtToken = async () => {
await axios.post(
'http://localhost:8080/authenticate',
{
username: 'username',
password: 'password'
}
).then(
(res) => {
console.log("JWT token fetch")
console.log(res)
this.setState({jwtToken: res.data.jwt})
}
)
}
and then calling this function as follows
processImage = () => {
this.fetchJwtToken();
console.log(this.state.jwtToken)
//use the token to make further calls
}
The function returns a pending promise due to which I think the await completes its execution. This results in empty JWT token to be set in the state.
I want to wait till the token is returned so that I can use it for further calls
How to make it wait till axios returns a fulfilled promise?
>Solution :
Hi you must send your promise in a variable like this and if you use await you can’t use .then you must doing like this :
fetchJwtToken = async () => {
let anyThing = await axios.post(
'http://localhost:8080/authenticate',
{
username: 'username',
password: 'password'
}
)
console.log(anyThing)
}