Using Vuex on a Nuxt2 application. A CRUD of categories has an index, a create and an update views. Every time the user enters the update or create view, an action is dispatched which is supposed to reset the state to its default values. However, this only works partially: the categories object is reset, but the sections and relatedFinishCategories arrays are not.
This is the state:
const defaultState = () => ({
selectedLanguage: null,
languages: null,
category: {
id: null,
active: null,
translations: {},
},
finishCategories: {},
sections: [],
relatedFinishCategories: [],
relatedFinishCategoriesTranslations: [],
loading: false,
fetching: true,
});
export default {
namespaced: true,
state: defaultState(),
getters: {
getSelectedLanguage(state) {
return state.selectedLanguage;
},
getLanguages(state) {
return state.languages;
},
getCategory(state) {
return state.category;
},
getFinishCategories(state) {
return state.finishCategories;
},
getFetching(state) {
return state.fetching;
},
getLoading(state) {
return state.loading;
},
getRelatedFinishCategories(state) {
return state.relatedFinishCategories;
},
getSections(state) {
return state.sections;
},
getState(state) {
return state;
}
},
mutations: {
SAVE_STATE(state) {
state = defaultState();
},
Create component's script:
<script>
import { mapGetters } from 'vuex';
export default {
computed: {
...mapGetters({
selectedLanguage: "productCategories/getSelectedLanguage",
category: "productCategories/getCategory",
languages: "productCategories/getLanguages",
finishCategories: "productCategories/getFinishCategories",
loading: "productCategories/getLoading",
fetching: "productCategories/getFetching",
sections: "productCategories/getSections",
relatedFinishCategories: "productCategories/getRelatedFinishCategories",
}),
},
async mounted() {
this.$store.dispatch('productCategories/resetState');
console.log(this.sections)
await this.$store.dispatch('productCategories/fetchAll');
console.log(this.sections)
// this.$store.dispatch('productCategories/initializeProductCategoryForm');
},
methods: {
async sendData() {
await this.$store.dispatch('productCategories/setLoading', true);
try {
await this.$store.dispatch('productCategories/sendForm');
await this.$store.dispatch('productCategories/fetchAll', this.category.id);
this.$modals.success();
this.$router.push(this.$route);
} catch (e) {
console.log(e.message);
} finally {
await this.$store.dispatch('productCategories/setLoading', false);
}
},
},
};
</script>
The action calling the SAVE_STATE mutation:
resetState({ commit }) {
commit('SAVE_STATE')
}