How to clear state in vuex store?

Solution 1:

I have just found the great solution that works for me.

const getDefaultState = () => {
  return {
    items: [],
    status: 'empty'
  }
}

// initial state
const state = getDefaultState()

const actions = {
  resetCartState ({ commit }) {
    commit('resetState')
  },
  addItem ({ state, commit }, item) { /* ... */ }
}

const mutations = {
  resetState (state) {
    // Merge rather than replace so we don't lose observers
    // https://github.com/vuejs/vuex/issues/1118
    Object.assign(state, getDefaultState())
  }
}

export default {
  state,
  getters: {},
  actions,
  mutations
}

Thanks to Taha Shashtari for the great solution.

Michael,

Solution 2:

Update after using the below solution a bit more

So it turns out that if you use replaceState with an empty object ({}) you end up bricking reactivity since your state props go away. So in essence you have to actually reset every property in state and then use store.replaceState(resetStateObject). For store without modules you'd essentially do something like:

let state = this.$store.state;
let newState = {};

Object.keys(state).forEach(key => {
  newState[key] = null; // or = initialState[key]
});

this.$store.replaceState(newState);

Update (from comments): What if one needs to only reset/define a single module and keep the rest as they were?

If you don't want to reset all your modules, you can just reset the modules you need and leave the other reset in their current state.

For example, say you have mutliple modules and you only want to reset module a to it's initial state, using the method above^, which we'll call resetStateA. Then you would clone the original state (that includes all the modules before resetting).

var currentState = deepClone(this.state)

where deepClone is your deep cloning method of choice (lodash has a good one). This clone has the current state of A before the reset. So let's overwrite that

var newState = Object.assign(currentState, {
  a: resetStateA
});

and use that new state with replaceState, which includes the current state of all you modules, except the module a with its initial state:

this.$store.replaceState(newState);

Original solution

I found this handy method in Vuex.store. You can clear all state quickly and painlessly by using replaceState, like this:

store.replaceState({})

It works with a single store or with modules, and it preserves the reactivity of all your state properties. See the Vuex api doc page, and find in page for replaceState.

For Modules

IF you're replacing a store with modules you'll have to include empty state objects for each module. So, for example, if you have modules a and b, you'd do:

store.replaceState({
  a: {},
  b: {}
})