Search code examples
vuejs2vuex

Vuex: How to properly add an dispatched action inside an action


After I make my post in a dispatched action such as saveDisplayLimitQuanity below, I make mutations to show a banner and then 5 seconds later, hide it.
I would have to add this logic to each dispatched action so it'd be a lot of repeated code.

saveDisplayLimitQuantity: (context, data) => {
    return axios.post(data.url, {
        display_limit: data.display_limit
    })
    .then(response => {
        context.commit('setShowBanner', true);
        context.commit('setBannerMessage', ['Display Limit Quantity Successully Updated!']);
        context.commit('setBannerStatus', 'Success');
        setTimeout(() => {
            context.commit('setShowBanner', false);
            context.commit('setBannerMessage', null);
            context.commit('setBannerStatus', null);
        }, 5000)
    })
    .catch(err => {
        context.commit('setShowBanner', true);
        context.commit('setBannerMessage', ['Something Went Wrong.  Please try again']);
        context.commit('setBannerStatus', 'Error');
        setTimeout(() => {
            context.commit('setShowBanner', false);
            context.commit('setBannerMessage', null);
            context.commit('setBannerStatus', null);
        }, 5000)
    })
},

I wanted to make an action I can put in the returned Promise that I can call each time and just pass in a message. I tried doing it this way by adding in dispatch as argument but it still isn't working:

saveDisplayLimitQuantity: (context, data, dispatch) => {
    return axios.post(data.url, {
        display_limit: data.display_limit
    })
    .then(response => {
        let data = {
             'status': 'Success', 
              'message': "Yay!"
        }
        dispatch('showBanner',data)
    })
    .catch(err => {
        let data = {
             'status': 'Error', 
              'message': "Please try again"
        }
        dispatch('showBanner',data)
    })
},

showBanner: (context,data) => {
    context.commit('showBanner', true);
    context.commit('bannerMessage', data.message);
    context.commit('bannerStatus', data.status);
}

Solution

  • It is not working, because you don't access the action showBanner properly. In your first example you used context.commit() to access a mutation. So in order to access the action you need to follow the same rule:

    Instead of passing the dispatch argument you simply need to call the action by it's context:

    context.dispatch('showBanner', data);
    

    Or even better use argument destructuring on the context object. It saves you from calling context over and over again:

    saveDisplayLimitQuantity({ dispatch }, data) {
       ... 
       dispatch('showBanner', data);
    }