Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 }},
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading