reactjsuse-reducer

UseReducer hook - Delete an item from array of objects


This is the data stored in the following reducer:

const[displayState, dispatchDisplayState]=useReducer(displayReducer,{
        data:[], searchResultData:[], display:null
    })

enter image description here

I'm trying to alter the state by removing a film (by ID) from the film array of objects within the data field

dispatchDisplayState({type:"REMOVE_FILM_FROM_DATA", filmid:filmid }) 

This isn't working:

const displayReducer=(state,action)=>{
    switch(action.type)
    {
        case 'REMOVE_FILM_FROM_DATA':
            return{...state, data:state.data.films.filter(item=>item._id!==action.filmid) }

        default: return{data:[], searchResultData:[], display:null}
    }
}

Solution

  • It looks like you need to target the films array directly. Something like this:

    data: {...state.data, films: state.data.films.filter(item=>item._id!==action.filmid)} 
    

    The way your code is written it looks like you are replacing the entire data property with the films property.