Mutating state does not update the view unless the view is re-rendered:
data () {
return {
products: this.$store.getters.allProducts
}
},
methods: {
deleteProduct (id) {
console.log(id)
this.$store.commit('removeProduct', id)
}
}
products remains the same even after the removeProduct is committed. Do I need to do any manual watch for this could it be a Vue related issue?
This is what the mutation method looks like; probably it could be the way I am mutating state:
removeProduct: (state, payload) => {
const index = state.products.indexOf(state.products.filter(p => p.id === payload)[0])
state.products = [
...state.products.slice(0, index),
...state.products.slice(index + 1)
]
}
I have created a plunkr in an attempt to replicate this.
data isn't updated reactively. You should use computed properties for this.
You could also make your removeProduct method more efficient by just using splice(index, 1). And to get the index you could just use findIndex() instead of indexOf + filter.
Thanks, @BartCorremans !!
Actually, using splice(index, 1) does the job but I am just worried it mutates data in this case.
It will only mutate your products array, which is what you want to happen anyway. :) It'll be much cheaper than creating several new arrays.
Awesome!! Thanks a lot. @BartCorremans one last quetion though... which part of the state should I not mutate? I thought everything in the state shouldn't be
Everything in the state can be mutated. The only "rule" is that it must be done through committed mutations so that they can be tracked.
I am using computed properties and splice, but it does not update for me.
...
<span v-for="question in sectionQuestions(sectionId)">{{ question.title }}</span>
...
computed: {
...mapGetters("assessment_designer", [
"sectionQuestions"
])
},
When I delete one of the questions using splice, the state looks correct, but the view does not reflect the change. I have also verified that sectionQuestions(...) is actually called again after the successful delete.
Most helpful comment
I am using computed properties and splice, but it does not update for me.
When I delete one of the questions using
splice, the state looks correct, but the view does not reflect the change. I have also verified thatsectionQuestions(...)is actually called again after the successful delete.