Using immutability-helper in React, update multiple values in one pass

Can you update two or more values in a nested state using one update method call from immutability-helper?

I tried the code below but only the last line [elementIndex]: {fouls: {$set: 1 }} gets implemented.

this.state={
    players:[{points: 0, fouls: 0, name: 'bob'}, {points: 0, fouls: 0, name: 'joe'}]
}

const element = this.state.players.findIndex(el => el.name === 'bob');

let score = update(this.state.players, {
      [element]: {points: {$set: 2 }},
      [element]: {fouls: {$set: 1 }}
    });

this.setState({ players: score})

>Solution :

The reason this isn’t working is because you can’t have duplicate keys in an object (ie two keys [element]).

I believe this will work: change your update statement to:

let score = update(this.state.players, {
  [element]: {points: {$set: 2 }, fouls: {$set: 1 }},
});

Leave a Reply