2

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 }
}
zcoop98
  • 2,590
  • 1
  • 18
  • 31
user3213700
  • 159
  • 1
  • 2
  • 9

2 Answers2

3

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' } */
})
zcoop98
  • 2,590
  • 1
  • 18
  • 31
Kordonme
  • 2,314
  • 3
  • 20
  • 32
0

Your code will work if the code that calls your action uses either 'await' or a callback.

For example:

const result = await store.dispatch('getData');

The main takeaway being that actions return promises even if the action isn't doing any asynchronous work!

omarjebari
  • 4,861
  • 3
  • 34
  • 32