Redux: help filtering out/deleting array item of a property in my reducer

Viewed 178

Hello So I want to give my reducer the ability to remove an item in an array of a property. I am working with a state of users that looks like this.

users = {
    'testUser1:{
            id:'',
            name:'',
            favorites:['oranges','apples'],
            lists:{
                myList:[]
            }
    },
}

I want to be able to delete items from the favorites property in my reducer.

here is my reducer so far

function usersReducer(state={},action){
    switch(action.type){
        case RECEIVE_USERS:
        return{
            ...state,
            ...action.users,
        }

        case ADD_FAVORITE:
        return{
            ...state,
            [action.authedUser]:{
                ...state[action.authedUser],
                favorites:
                    state[action.authedUser].favorites.concat([action.favorite])                
            }
        }

        case DELETE_FAVORITE:

            /*const newArray = Object.values(action.authedUser.favorites).filter((item)=>
                item !== 'oranges'
            )           */
            
        }
    }
}
2 Answers

Ok. Based on what I've read I assume that your related reducer actions return the Entire User object in question.

So, I am assuming the action for ADD_FAVORITE will return the User object as a response as well as the name of the favorite element in string format for the favorites array?

So for the DELETE_FAVORITE action, it should return the User object as well as the string value of the favorite object to be removed.

So as I see you attempted, a filter should work in this case.

        case DELETE_FAVORITE:
        return{
            ...state,
            [action.authedUser]:{
                ...state[action.authedUser],
                favorites: action.authedUser.favorites.filter(word => word != action.favorite),
            }
        }

Super close

const newFavorites = state[action.authedUser].favorites.filter(item =>
  item !== action.favorite
);

return {
  ...state,
  [action.authedUser]: {
    ...state[action.authedUser],
    favorites: newFavorites,
  }
};

You want to filter out the item that matches action.favorite (or however you decide to name it) and then set that new array as the user's favorites.

Related