3

I'm trying to update part of my redux state, which contains two objects nested inside another object. Usually when updating a javascript object immutably I would use the spread operator, then define any changes afterwards as follows:

state = {...state, property1: newvalue} 

However, im unsure how to use the spread operator when i have nested objects. Here is the relevant code and my attempt:

const squadDatabase = {currentSquad: {
    0: null,
    1: null,
    2:null

    }, newAdditions: null}

export default (state=initial_squad, action)=>{

    switch(action.type){
        case ADD_PLAYER_TO_SQUAD:
            return {...state, currentSquad[action.payload.currentSquadMemberId]:action.payload.newSquadAdditionId, newAdditions: action.payload.newSquadAdditionId}
        default:
            return initial_squad
    }
}

Does anyone have any idea how to immutably update nested javascript objects, using the spread operator or otherwise?

Sean
  • 587
  • 4
  • 20
  • {...state, currentSquad: {...state['currentSquad'], [action.payload.currentSquadMemberId]:action.payload.newSquadAdditionId}, newAdditions: action.payload.newSquadAdditionId} – Shivam Gupta Nov 19 '19 at 22:20
  • Does this answer your question? [Spread syntax for nested javascript object with dynamic properties for grouping](https://stackoverflow.com/questions/54582984/spread-syntax-for-nested-javascript-object-with-dynamic-properties-for-grouping) – Heretic Monkey Nov 19 '19 at 22:54

1 Answers1

8

Basically you have to add second level of object (state) destructuring.

return {
   ...state, // first nesting level spread
   currentSquad: {
      ...this.state.currentSquad, // second nesting level spread
      currentSquad[action.payload.currentSquadMemberId]: action.payload.newSquadAdditionId, 
   },
   newAdditions: action.payload.newSquadAdditionId,
};
kind user
  • 40,029
  • 7
  • 67
  • 77