Categories
Vue Answers

How to clear state in a Vuex store?

Spread the love

Sometimes, we want to clear state in a Vuex store.

In this article, we’ll look at how to clear state in a Vuex store.

How to clear state in a Vuex store?

To clear state in a Vuex store, we can call Object.assign.

For instance, we write

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

const state = getDefaultState();

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

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

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

to add the resetState mutation that calls Object.assign with state and the object returned by getDefaultState to merge the property values from the object returned by getDefaultState into state.

This will reset the state property values to the ones listed in the object in getDefaultState.

Conclusion

To clear state in a Vuex store, we can call Object.assign.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *