how do I clearInterval a vuejs state

Viewed 610

I have the following code in my vuex:


export default new Vuex.Store({
    state: { 
        intervalVar: 0
    },

    mutations: {
        SET(state, {key, value}) {
            state[key] = value
        },
    },

    actions: {
        doSomething({commit}) {
            commit("SET", {
                key: 'intervalVar',
                value: setInterval( () => console.log('hi'), 30000)
            })
        }, 
    }, 
})

as you see I give setInterval value to state.intervalVar but I have no idea how I can do cleareInterval on state.intervalVar.

2 Answers

You can call SET mutation with 0 value:

actions: {
    clearInterval({state, commit}) {
        clearInterval(state.intervalVar)
        commit("SET", {
            key: 'intervalVar',
            value: 0,
        })
    }, 
}, 

Can't just add another action to clear the interval?

export default new Vuex.Store({
    state: { 
        intervalVar: 0
    },
    mutations: {
        SET(state, {key, value}) {
            state[key] = value
        },
        CLEAR(state, key) {
            clearInterval(state[key]);
        }
    },

    actions: {
        async doSomething({commit}) {
            commit("SET", {
                key: 'intervalVar',
                value: setInterval( () => console.log('hi'), 30000)
            })
        },
        clearSomething({ commit }) {
            commit('CLEAR', 'intervalVar');
        }
    }, 
})
Related