Answer a question

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'
            )           */
            
        }
    }
}

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),
            }
        }
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐