Zoomzoom
Zoomzoom

Reputation: 189

Update a nested state in a reducer React Redux

I'm using redux with reactjs. Here's my reducer state :

{
 XSAUZHNAKZJ : //id User
  {
   AZRAERAZEAZ : //id Conversation - always one object 
    {
     timestamp : 123123123,
     lastMessage : "hello"
    }
  },
 BLZEJARNAELKR : //id User
  {
   AANALZKJAZ : //id Conversation - always one object
    {
     timestamp : 123123123,
     lastMessage : "hello"
    }
  }
}

I want to update the reducer and add a key/value ('name' : joe) just after lastMessage. I have the value of name (ex : joe) and an id User (ex : XSAUZHNAKZJ) in my action.payload. Here's my code, but it seems that I'm not doing right.

export default function(state={},action){
  switch(action.type){
    case 'GET_USER_INFO':
      var tempState = Object.assign({}, state);
      var conversation = tempState[action.payload.key];
      var conversationDetail = conversation[Object.keys(conversation)[0]];
      conversationDetail['name']=action.payload.val().name;
      return tempState;
    default:
      return state;
  }
}

Upvotes: 2

Views: 689

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281686

Make use of immutability helper to assign the new object to the nested state

import update from 'immutability-helper';

export default function(state={},action){
  switch(action.type){
    case 'GET_USER_INFO':
         return update(state, {
             [action.payload.key]: {
                   [Object.keys(state[action.payload.key])[0]]: {
                          $merge: {name: action.payload.name}
                   }
             }
         })
    default:
      return state;
  }
}

Upvotes: 2

Related Questions