timpone
timpone

Reputation: 19979

removing an item from an array in Vuex

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?

Upvotes: 3

Views: 15885

Answers (3)

Anand From Pie.host
Anand From Pie.host

Reputation: 1233

You can use the following mutation, it uses the splice from Javascript array methods.

deleteElement: function(state.element) {
  state.myArray.splice(this.events.indexOf(element), 1);
}

If you know the index of the element, it becomes (obviously):

deleteElement: function(state,elementIndex) {
  state.myArray.splice(elementIndex, 1);
}

"1" is the number of elements to remove, starting from elementIndex

Upvotes: -2

Rakibul Haq
Rakibul Haq

Reputation: 1398

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);
  }

Upvotes: 16

acdcjunior
acdcjunior

Reputation: 135862

If you have undefined as elements of the liked_items array, you'll get obj as undefined sometimes.

You could simplify your if as below, though:

 state.user.liked_items.find((obj,i) => {
   if(obj && obj.global_id === global_id){

Or could pre-filter the array to keep only non-undefined values:

 state.user.liked_items.filter(o => o).find((obj,i) => {
   if(obj.global_id === global_id){

Upvotes: 2

Related Questions