How to Clear/Reset Vuex Module State to Default

Hi artisans, we know that Vuex is a state management pattern + library for Vue.js applications. Sometimes, we need to clear or reset vuex store. In this article, we’re going to learn how to do that. Let’s get started:

Cart Example

Nagivate to store folder and create cart.js file.

store/cart.js
const getDefaultState = () => {
  return {
    items: []
  }
}

// initial state
const state = getDefaultState()

const mutations = {
  RESET_STATE(state) {
    Object.assign(state, getDefaultState())
  }
}

const actions = {
  resetState({ commit }) {
    commit('RESET_STATE')
  },
  addToCart ({ state, commit }, item) {
    //
  }
}

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

Now call resetCartState action from anywhere like:

this.$store.dispatch('cart/resetState');
That’s it. Thanks for reading. ?

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.