Reputation: 1445
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.
Upvotes: 2
Views: 3771
Reputation: 206
You have to search, mapGetters, mapActions and you have to check async function
for example
if you request to api you can do this.
//api.js
import axios from 'axios'
export aync function getuser() {
...
...
const data = await axios.get(url,{params:{....}})
return data
}
//component
import {getuser} from '@/app.js'
import {mapAction} from 'vuex'
data() {
return {
data:null
}
}
methods: {
..mapAction('getUserAction')
async getUserMethod () {
this.data = await getuser()
this.getUserAction(this.data)
}
}
//store.js
actions: {
getUserAction () {
// your actions..
}
}
Upvotes: 0
Reputation: 4991
In the first block, your then
doesn't return anything : therefore it returns undefined
. Returning the resolved value should fix this issue.
Upvotes: 2