Search code examples
javascriptvue.jsvuejs2vue-componentvuex

How to access an action or make a dispatch from inside the store


This is a notification module in the store, I want to trigger the clear method from within the store itself to close each notification when they get triggered automatically after a couple of seconds. How can I achieve that?

export const mutations = {
    success(state, message, isModal) {
        state.type = 'success';
        state.message = message;
        state.show = true;
        state.isModalMsg = isModal;
        setTimeout(()=>{
            actions.clear(state);
        },3000);
    },
    error(state, message, isModal) {
        state.type = 'danger';
        state.message = message;
        state.show = true;
        state.isModalMsg = isModal;
    },
    clear(state) {
        state.type = null;
        state.message = null;
        state.show = false;
        state.isModalMsg = false;
    }
};

export const actions = {
    success({ commit }, message) {
        commit('success', message);
    },
    error({ commit }, message) {
        commit('error', message);
    },
    clear({ commit }) {
        commit('clear');
    }

Solution

  • Use dispatch from within the success action:

    success({ commit, dispatch }, message) {
        commit('success', message);
        setTimeout(() => {
            dispatch('clear');
        }, 2000)
    },