I am having some difficulty using a promise returned by axios in two places. I want to use .then()
inside of my Vuex action to commit a change to my state, return the axios promise and use .then()
again inside my component to update the UI. The issue I have encountered is that the promise response is undefined inside my component.
// component
methods: {
getUser(userId) {
this.$store.dispatch('GET_USER', userId)
.then(response => {
console.log(response); // undefined
});
}
}
// vuex
actions: {
GET_USER: ({commit}, userId) => {
return api.getUserById(userId)
.then(({data}) => {
commit('ADD_USER', data);
});
}
}
// api service
getUserById(userId) {
return axios.get('/api/users/' + userId);
}
If I remove the use of .then()
inside my Vuex action, response
becomes the object from my api, but I'd like to have a promise in my component so that i can catch
errors.
// component
methods: {
getUser(userId) {
this.$store.dispatch('GET_USER', userId)
.then(response => {
console.log(response); // no longer undefined
});
}
}
// vuex
actions: {
GET_USER: ({commit}, userId) => {
return api.getUserById(userId); // removed 'then' method
}
}
What is wrong in the first code block?
Thanks.
then
doesn't return anything (therefore returnsundefined
) - Vivickdata
from inside the firstthen
worked. Thank you. You're welcome to write an answer so you can earn rep. - brad