Actions

Try this lesson on Scrimba

Actions are similar to mutations, the differences being that:

  • Instead of mutating the state, actions commit mutations.
  • Actions can contain arbitrary asynchronous operations.

Let’s register a simple action:

  1. const store = createStore({
  2. state: {
  3. count: 0
  4. },
  5. mutations: {
  6. increment (state) {
  7. state.count++
  8. }
  9. },
  10. actions: {
  11. increment (context) {
  12. context.commit('increment')
  13. }
  14. }
  15. })

Action handlers receive a context object which exposes the same set of methods/properties on the store instance, so you can call context.commit to commit a mutation, or access the state and getters via context.state and context.getters. We can even call other actions with context.dispatch. We will see why this context object is not the store instance itself when we introduce Modules later.

In practice, we often use ES2015 argument destructuring to simplify the code a bit (especially when we need to call commit multiple times):

  1. actions: {
  2. increment ({ commit }) {
  3. commit('increment')
  4. }
  5. }

Dispatching Actions

Actions are triggered with the store.dispatch method:

  1. store.dispatch('increment')

This may look silly at first sight: if we want to increment the count, why don’t we just call store.commit('increment') directly? Remember that mutations have to be synchronous. Actions don’t. We can perform asynchronous operations inside an action:

  1. actions: {
  2. incrementAsync ({ commit }) {
  3. setTimeout(() => {
  4. commit('increment')
  5. }, 1000)
  6. }
  7. }

Actions support the same payload format and object-style dispatch:

  1. // dispatch with a payload
  2. store.dispatch('incrementAsync', {
  3. amount: 10
  4. })
  5. // dispatch with an object
  6. store.dispatch({
  7. type: 'incrementAsync',
  8. amount: 10
  9. })

A more practical example of real-world actions would be an action to checkout a shopping cart, which involves calling an async API and committing multiple mutations:

  1. actions: {
  2. checkout ({ commit, state }, products) {
  3. // save the items currently in the cart
  4. const savedCartItems = [...state.cart.added]
  5. // send out checkout request, and optimistically
  6. // clear the cart
  7. commit(types.CHECKOUT_REQUEST)
  8. // the shop API accepts a success callback and a failure callback
  9. shop.buyProducts(
  10. products,
  11. // handle success
  12. () => commit(types.CHECKOUT_SUCCESS),
  13. // handle failure
  14. () => commit(types.CHECKOUT_FAILURE, savedCartItems)
  15. )
  16. }
  17. }

Note we are performing a flow of asynchronous operations, and recording the side effects (state mutations) of the action by committing them.

Dispatching Actions in Components

You can dispatch actions in components with this.$store.dispatch('xxx'), or use the mapActions helper which maps component methods to store.dispatch calls (requires root store injection):

  1. import { mapActions } from 'vuex'
  2. export default {
  3. // ...
  4. methods: {
  5. ...mapActions([
  6. 'increment', // map `this.increment()` to `this.$store.dispatch('increment')`
  7. // `mapActions` also supports payloads:
  8. 'incrementBy' // map `this.incrementBy(amount)` to `this.$store.dispatch('incrementBy', amount)`
  9. ]),
  10. ...mapActions({
  11. add: 'increment' // map `this.add()` to `this.$store.dispatch('increment')`
  12. })
  13. }
  14. }

Composing Actions

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?

The first thing to know is that store.dispatch can handle Promise returned by the triggered action handler and it also returns Promise:

  1. actions: {
  2. actionA ({ commit }) {
  3. return new Promise((resolve, reject) => {
  4. setTimeout(() => {
  5. commit('someMutation')
  6. resolve()
  7. }, 1000)
  8. })
  9. }
  10. }

Now you can do:

  1. store.dispatch('actionA').then(() => {
  2. // ...
  3. })

And also in another action:

  1. actions: {
  2. // ...
  3. actionB ({ dispatch, commit }) {
  4. return dispatch('actionA').then(() => {
  5. commit('someOtherMutation')
  6. })
  7. }
  8. }

Finally, if we make use of async / await, we can compose our actions like this:

  1. // assuming `getData()` and `getOtherData()` return Promises
  2. actions: {
  3. async actionA ({ commit }) {
  4. commit('gotData', await getData())
  5. },
  6. async actionB ({ dispatch, commit }) {
  7. await dispatch('actionA') // wait for `actionA` to finish
  8. commit('gotOtherData', await getOtherData())
  9. }
  10. }

It’s possible for a store.dispatch to trigger multiple action handlers in different modules. In such a case the returned value will be a Promise that resolves when all triggered handlers have been resolved.