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
.