Reputation: 2877
My store action returns a value that I want to check when calling that action from my component. But for some reason, all I'm getting is undefined
instead of any of the values I'm actually returning from any action.
Why?
Store action:
export const actions = {
async initialize ({ state, commit, dispatch }) {
await this.$axios.get('myEndpoint')
.then((res) => {
return true
}).catch((error) => {
return false
})
}
}
Component code:
async mounted () {
const initializeResult = await this.initialize()
console.log(initializeResult)
}
Upvotes: 1
Views: 41
Reputation: 1
You've to respect the vuex store pattern, First you should create a state that could be mutated inside a mutation which also could be committed inside the async callback in your action :
export const state={
initResult:null
}
export const mutations={
SET_RESULT(state,payload){
state.initResult=payload
}
}
export const actions = {
async initialize ({ state, commit, dispatch }) {
await this.$axios.get('myEndpoint')
.then((res) => {
commit('SET_RESULT',true)
}).catch((error) => {
commit('SET_RESULT',false)
})
}
}
then in your component dispatch the action inside the mounted hook and return the state using a computed property :
computed:{
result(){
return this.$store.initResult;
}
},
mounted () {
this.$store.dispatch('initialize')
}
Upvotes: 1