Someone Special
Someone Special

Reputation: 13588

Redux Nested State... with dynamic key

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?

Upvotes: 3

Views: 4599

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281874

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
                }
            }
         };

Upvotes: 10

Related Questions