Almog
Almog

Reputation: 2837

Redux remove item from state based on object value

I have the following state in my redux store, it's photos which has an array of objects enter image description here

Each object is different, I need to be able to find the object with the filename and remove the entire array item I have tried with index and the following but not really working

case actionTypes.PHOTO_DELETE:
           // return state.filter((photo) => photo.filename !== action.data)

            return { photos: state.photos.filter(photo =>
                photo.filename !== action.data
            )}

           // let index = state.photos.findIndex((photo) => photo.fillname === action.data);
            //console.log(index)
            /*
            var index = _.findIndex(action.data, function(photos) {
                return photos.photos == action.data
            })
            */
            //return update(state, {photoGroups: {$splice: [[index]]}});

Upvotes: 0

Views: 1263

Answers (3)

Fawaz
Fawaz

Reputation: 3560

The problem with your approach is that you are running comparison on the photos array, whereas there is another array within photos array in your json data. So in order to fix this, use filter within filter to reach the photo object and compare the filename.

 return { 
   photos: state.photos.filter(photos => {
     const match = photos.filter(photo => (photo.filename === action.data));
     // return false if match is found
     // thus removing photos array from the data
     return !(match && match.length);
   })
 };

Upvotes: 0

Wicharek
Wicharek

Reputation: 301

Filter the photos array by checking if the object with specified filename does not exist in the inner array. If it doesn't then findIndex() === -1.

return {
  photos: state.photos.filter(photo =>
    photo.findIndex(object => object.filename === action.data) === -1
  )
}

Upvotes: 1

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

You can destruct the array so you don't mutate it:

const index = state.photos.findIndex(photos => 
  !photos.filter(photo => photo.filename === action.data)
)

return {
   ...state,
   photos: [
     ...state.photos.slice(0, index),
     ...state.photos.slice(index + 1),
  ],
}

Upvotes: 0

Related Questions