Vue Vuex: reset store state to default / initial

Vuex is amazing tool for Vue, and I’ve already written a post about one of its adoption in web application: to avoid multiple ajax requests from many component instances. Of course, there are many, many options how to use Vuex in our app, and the most common is standard store with modules data. It’s great, but there is one important problem: default state and option to reset state. Vuex doesn’t have build-in option to reset state to default, defined in store declaration, so many users write additional commits and mutations for that, or one, which copies the same props as initial state. It’s ok, but means, that we must duplicate the same code, and if we want to change initial state, we must also change reset method.

I don’t like such solutions: it’s real mess and may causes a lot of issues when our app grows. With Vuex, growing is not a problem, so, we will often make issues here and will forget about updating reset method. I really don’t know, why there is no build-in reset method, but last time must fight with that and decided to find better solution than duplicate code. It’s very simple to implement, and I decided to share it as this small post. First of all, we must create new file, for example state.js for out module store. It will contain default state:

export default {
    foo: 'bar',
    myProp: false,
    myObj: {
        foo1: 'bar1',
        foo2: 'bar2'
    }
}

Then, we can use it in store declaration:

import * as actions from './actions'
import * as mutations from './mutations'
import state from './state'

export default {
    namespaced: true,
    namespace: 'mynamespace/',
    state () {
        return {...state}
    },
    actions,
    mutations
}

And there is time to magic. We must create new action and mutation and simply use our store.js file to reset initial store state:

// actions.js
export const resetState = function ({commit, dispatch}) {
    commit('RESET_STATE')
}

// mutations.js
import defaultState from './state'

export function RESET_STATE (state) {
    Object.assign(state, defaultState)
}

And it’s all. If we want to add something to initial state, we must edit only store.js: simple and clean, without any duplicates. In that case I use different files for actions/commits, but if you have it in the same as store declaration, you don’t have to import state.js more than one time of course.