async login(context, payload) {
const response = await axios
.post(
'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyCQ6w2jvJVNrOwON4-KnEOV1kH-ckEDokg',
{
email: payload.email,
password: payload.password,
returnSecuredToken: true
},
{
Headers: {
'Content-Type': 'application/json'
}
}
)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
console.log(error.response);
});
console.log(response);
context.commit('setUser', {
token: response.data.idToken,
userId: response.data.userId,
tokenExpiration: response.data.expiresIn
});
Hello, maybe it's a dumb question but how can I console.log my response there ? I tried to stock my response in a const but it's the same issue, the console log and the commit execute before the await async and I can't use any data that return from the axios response, thanks if you take the time to help me.
The problem is your intermediate .then
returns nothing, so the return value of await axios.post()
resolves to undefined
:
const response = await axios
.post(/*...*/)
.then(function(response) {
// ❌ nothing returned here, so response at the top is undefined
})
.catch(/*...*/);
console.log(response); // => undefined
You could either refactor the promise chain into a try/catch
:
try {
const response = await axios.post(/*...*/);
console.log(response); // => ✅
context.commit('setUser', /*...*/);
} catch (error) {
console.log(error);
}
...or return the inner response
in .then
:
const response = await axios
.post(/*...*/)
.then(function(response) {
return response; // 👈
})
.catch(/*...*/);
console.log(response); // => ✅
context.commit('setUser', /*...*/);
Note: The latter approach (mixing await
with a promise chain) is typically discouraged, as it reduces readability/maintainability.