225

I have the following setup for my actions:

get1: ({commit}) => {
  //things
  this.get2(); //this is my question!
},
get2: ({commit}) => {
  //things
},

I want to be able to call one action from within another, so in this example I want to be able to call get2() from within get1(). Is this possible, and if so, how can I do it?

Gass
  • 7,536
  • 3
  • 37
  • 41
muttley91
  • 12,278
  • 33
  • 106
  • 160

5 Answers5

439

You have access to the dispatch method in the object passed in the first parameter:

get1: ({ commit, dispatch }) => {
  dispatch('get2');
},

This is covered in the documentation.

kissu
  • 40,416
  • 14
  • 65
  • 133
thanksd
  • 54,176
  • 22
  • 157
  • 150
  • 1
    Is there a way to do something once an action is complete? Basically use this with a `then()`? – muttley91 Aug 24 '17 at 01:53
  • 4
    Yep, it's fully covered in the documentation page I linked – thanksd Aug 24 '17 at 12:44
  • 3
    How can I dispatch an action from another store? e.g. in store A I want to do `dispatch('B/someaction')` – A.W. Jun 15 '18 at 17:55
  • 3
    @Guus https://stackoverflow.com/questions/42984132/is-there-a-way-to-dispatch-actions-between-two-namespaced-vuex-modules – thanksd Jun 15 '18 at 17:57
18

You can access the dispatch method through the first argument (context):

export const actions = {
  get({ commit, dispatch }) {
    dispatch('action2')
  }
}

However, if you use namespaced you need to specify an option:

export const actions = {
  get({ commit, dispatch }) {
    dispatch('action2', {}, { root: true })
  }
}
17axaH
  • 464
  • 5
  • 9
12

for actions that does not require payload

actions: {
    BEFORE: async (context, payload) => {
    },
    AFTER: async (context, payload) => {
        await context.dispatch('BEFORE');
    }
}

for actions that does require payload

actions: {
    BEFORE: async (context, payload) => {
    },
    AFTER: async (context, payload) => {
        var payload = {}//prepare payload
        await context.dispatch('BEFORE', payload);
    }
}
kissu
  • 40,416
  • 14
  • 65
  • 133
Rishabh Agrawal
  • 1,998
  • 2
  • 25
  • 40
5

we can pass parameters also while dispatching.

dispatch('fetchContacts', user.uid);
kissu
  • 40,416
  • 14
  • 65
  • 133
sau0409
  • 153
  • 1
  • 5
3
export actions = {
  GET_DATA (context) {
     // do stuff
     context.dispatch('GET_MORE_DATA');
  },

  GET_MORE_DATA (context) {
    // do more stuff
  }
}
kissu
  • 40,416
  • 14
  • 65
  • 133
Dazzle
  • 2,880
  • 3
  • 25
  • 52