3

My chat app requires a state where i can keep track of the object

messages.roomId.messageId.payload

where payload will contain the body of the messages object.

Currently whenever my new messages comes in I have the following reducer

    case 'NEW_MESSAGE':
        return {
            ...state,
             messages: {
                ...state.messages, 
                    [action.roomId]: { //Missing something here.
                        [action.id]:
                            action.payload
                    }
                }
             };

So I realise there's always only one message, within the room Id, since i did not use ... to maintain the previous state..

So i tried the following.

    case 'NEW_MESSAGE':
        return {
            ...state,
             messages: {
                ...state.messages, 
                    [action.roomId]: {
                        ...state.messages.[action.roomId], [action.id]: //Giving me error here.
                            action.payload
                    }
                }
             };

The error that came out was

..state.messages.[action.roomId], [action.id]: action.payload

where it doesn't accept .[action.roomId]

How should i place the dynamic key there so my reducer works?

1 Answer 1

10

When you are using the brackets notation, you don't have to use the dot notation to access object keys, you would simply write

...state.messages[action.roomId]

Your complete code would be

case 'NEW_MESSAGE':
    return {
        ...state,
         messages: {
            ...state.messages, 
                [action.roomId]: {
                    ...state.messages[action.roomId], [action.id]: 
                        action.payload
                }
            }
         };
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.