Can I return data from a Vuex action or do I need to update the store?
I've got an action defined but it returns no data:
getData() {
return { "a" : 1, "b" : 2 }
}
You can actually return data from an action. From the documentation:
Actions are often asynchronous, so how do we know when an action is done? And more importantly, how can we compose multiple actions together to handle more complex async flows?
You should return a promise and the data in the resolve()
method:
actions: {
actionA () {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ name: 'John Doe' })
}, 1000)
})
}
}
And use it this way:
store.dispatch('actionA').then(payload => {
console.log(payload) /* => { name: 'John Doe' } */
})