Updating state of vuex array when one item has some changes
JavaScript (not specific to Vue) can not detect setting the value of an Array item directly by index arr[3] = 'stop';
It also can not detect adding a new key or deleting an existing key from an Object.
You must be defining the initial state of the store, e.g.
const store = new Vuex.Store({
state: {
objects: []
},
mutations: {
EDIT_CASE (state, payload) {
const index = state.objects.findIndex(item => item.id === payload.id);
if (index !== -1) state.objects.splice(index, 1, payload);
}
}
})
There is no array issue with your example because you try to change an object property - not array element reference.
The problem is in Object.assign(item, payload.case_status);
- you should provide an object not just a field.
(Also you said that array called cases
but example has objects
, maybe this is problem too);
So this should work:
EDIT_CASE (state, payload) {
const item = state.objects.find(item => item.id === payload.recordId);
Object.assign(item, payload);
}
The error:
undefined is not an object
I think, it is related to Object.assign
because you pass field to it which is undefined probably.
P.S. There is small example to help you understand when array issue appears and when everything works fine. See code comments :)
new Vue({
el: "#app",
data: {
todos: [
{ text: "Learn JavaScript" },
{ text: "Learn Vue" },
{ text: "Play around in JSFiddle" },
{ text: "Build something awesome" }
]
},
methods: {
// work because object property is reactive
changeItemProperty() {
this.todos[3].text = "changedItemProperty";
},
// same reason, properties are reactive
changeItemWithAssign() {
Object.assign(this.todos[3], { text: "changedItemWithAssign" });
},
// does not work, can not track changes in array
// also this will break all attempts to change TEXT property in UI
// because property becomes not reactive after this due to new object
// try to changeItemProperty or changeItemWithAssign - does not work!
// changeItem2 will fix it :)
changeItem() {
this.todos[3] = { text: "changedItem" }
},
// works
changeItem2() {
Vue.set(this.todos, 3, { text: "changedItem2" });
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
<div v-for="todo in todos" :key="todo.text">
{{todo.text}}
</div>
<button @click="changeItemProperty">changeItemProperty(works)</button>
<button @click="changeItemWithAssign">changeItemWithAssign(works)</button>
<button @click="changeItem">changeItem(does not work!)</button>
<button @click="changeItem2">changeItem2(works)</button>
</div>