Recently, while sharing the state across different components using Vuex store, a co-worker accidentally added a new property to the store without following the proper action dispatching or mutation committing process. Surprisingly, nothing crashed and the application continued to run smoothly. Is there any method to prevent such incidents in the future?
This is how our current store structure looks like (simplified):
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
options: {},
},
actions: {
setAttributes (context, payload) {
context.commit('setAttributes', payload);
},
setPrice (context, payload) {
context.commit('setPrice', payload);
}
},
mutations: {
setAttributes (state, payload) {
state.options.width = payload.width;
state.options.height = payload.height;
},
setPrice (state, payload) {
state.options.price = payload.price;
},
},
getters: {
options: state => {
return state.options
}
}
});
And here's how the Vue instance is structured:
import Vue from 'vue';
import { mapGetters } from 'vuex';
import { store } from './store/store';
new Vue({
el: '#app',
store,
computed: {
...mapGetters([
'options',
])
},
mounted() {
this.$store.dispatch('setAttributes', {
width: 100,
height: 80,
});
}
});
To update the price, traditionally I would have used:
this.$store.dispatch('setPrice', {
price: 800,
});
However, we discovered that direct modification works as well:
this.options.price = 800;
Is there a way to prevent this or should we consider avoiding nested objects in the shared state altogether?