Skip to content Skip to sidebar Skip to footer

Spread Operator Overwriting Elements In New Object Instead Of Combining

I'm getting data from my API, and passing it through normalizr before dumping it into redux. When I get people data from the API the reducer should append them to the people store.

Solution 1:

That's because spread will not combine the objects recursively.

Take a look at this simple example where it works as you expected:

conststate= { 
    entities: { 
                people : { 
                          1 : { id:1, name:"jim" },
                          2 : { id:2, name:"billy" }
                         }
              },
    result : [ 1, 2 ]
}

constpayload= { 
    entities: { 
                people : { 
                          7 : { id:7, name:"sally" },
                          8 : { id:8, name:"ana" }
                         }
              },
    result : [ 7, 8 ]
}

constnew_state= { 
    entities: { 
                people : { 
                          ...state.entities.people,...payload.entities.people
                         }
              },
    result : [...state.result,...payload.result]
}

console.log(new_state)

Post a Comment for "Spread Operator Overwriting Elements In New Object Instead Of Combining"