How to Clear/Reset Vuex Module State to Default

Published on November 26, 2020 22 sec read

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. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write article on Laravel, Linux server, modern JavaScript and more on web development.

Follow