I am just starting using Vuex but am having a problem (and this could be some clueless syntax error on my part). I have a user with liked_items and have a network call that is to unlike an item.
mutations: {
SET_TOGGLE_LIKED: (state, { global_id }) => {
alert('here is global_id: ' + global_id)
state.user.liked_items.find((obj,i) => {
if(obj.global_id === global_id){ // no global_id
console.log('that exists at i: ' + i + ' with length: ' + state.user.liked_items.length)
state.user.liked_items.splice(i, 1)
console.log('that exists at i: ' + state.user.liked_items.length)
}else{
console.log('that doesnot exist!')
}
})
}
The problem I'm having is that after removing an item from the liked_items list, that seems to get recalled and I get an error that global_id does not exist on undefined.
I am able to fix by having:
state.user.liked_items.find((obj,i) => {
if(obj){
if(obj.global_id === global_id){
but why do I need to check for the existence of obj here?
We can also use map to get the index of the object in a store array and remove it using:
Mutation
REMOVE_OBJECT_FROM_ARRAY: (state, payload) => {
const i = state.someArrayofObjects.map(item => item.id).indexOf(payload.id);
state.someArrayofObjects.splice(i, 1);
}
Here, the id is the id passed with the payload to the MUTATION, we can also pass only the id as the whole payload. In that case, we can do something like:
REMOVE_OBJECT_FROM_ARRAY: (state, payload) => {
const i = state.someArrayofObjects.map(item => item.id).indexOf(payload);
state.someArrayofObjects.splice(i, 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With