How to clear state in vuex store?

KaliCharan picture KaliCharan · Feb 17, 2017 · Viewed 64.8k times · Source

My state in vuex store is huge.

Is there a way to reset all the data in state in one go, instead of manually setting everything to null?

Answer

Michael Horojanski picture Michael Horojanski · Aug 2, 2018

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,