'Returning data from a Vuex action

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 }
}


Solution 1:[1]

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' } */
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zcoop98