renakre
renakre

Reputation: 8291

Remove object by the key-index in redux state

I have the groups and members object with the following structure in the redux state:

groups :{
    '1683': {
      id: 1683,    
      members: [
        '1',
        '2'
      ],
    },
    '1900': {...}
}

members: {
   '1': {
       name: 'user1'
    }, 
   '2': {
       name:'user2'
    }
}

I have the following code in the reducer to remove a member from groups. The first part where I update the members error inside the group is working fine. But, the code where I want to remove the targeted member from the members object itself is not working. I tried splice but it is not working since members is not an array. I wonder how I can remove the member based on the key-id match. Any suggestions?

    case REMOVE_STUDENT_SUCCESS:
        return {
            ...state,
            groups: {
                ...state.groups,
                [action.payload.groupId]: {
                    ...state.groups[action.payload.groupId],
                    members: state.groups[action.payload.groupId].members.filter(id => id !== action.payload.studentId)
                }
            },

            //NOT WORKING
            //members: state.members.splice(action.payload.studentId, 1)
        };

Upvotes: 1

Views: 449

Answers (3)

Robert C
Robert C

Reputation: 60

I would highly recommend using Immutability-helper library. It makes modifying the immutable state much easier.

Also there is immer library which can help as well.

Upvotes: 1

Bashar Qaddumi
Bashar Qaddumi

Reputation: 36

This solution will work fine:

case REMOVE_STUDENT_SUCCESS: {

    var { members } = this.state;
    for (var property in members) {
      if (members.hasOwnProperty(property)) {
        property == studentId && delete members[property];
      }
    }
        return {
            ...state,
            groups: {
                ...state.groups,
                [action.payload.groupId]: {
                    ...state.groups[action.payload.groupId],
                    members: state.groups[action.payload.groupId].members.filter(id => id !== action.payload.studentId)
                }
            },

            members: members,


        };
    }

Upvotes: 0

Gangadhar Gandi
Gangadhar Gandi

Reputation: 2252

I think this is due to type casting, Convert the action payload's studentId value to string. The below will work,

case REMOVE_STUDENT_SUCCESS:
        return {
            ...state,
            groups: {
                ...state.groups,
                [action.payload.groupId]: {
                    ...state.groups[action.payload.groupId],
                    members: state.groups[action.payload.groupId].members.filter(id => id !== action.payload.studentId.toString())
                }
            },

            //NOT WORKING
            //members: state.members.splice(action.payload.studentId, 1)
        };

Upvotes: 0

Related Questions