-4

For example if a state is like this

state={
   reports:[{name:'nadib',age:23},{name:'nadib2',age:24}]
}

how can I change nadib2 to john with setState method?

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400

1 Answers1

1

You can use the functional setState syntax and create a copy using map to prevent mutation of the current state.

Then inside the loop, return the original object if you do not wish to modify. For the object that you need to modify, you could find it with a ternary operator and copy all existing keys, optionally modifying the other keys like shown.

this.setState(prevState => {
   return { 
            reports : prevState.reports.map(item => 
                       item.name === 'nadib2' ? ({...item, name: 'john'}) : item) 
          };
});
Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25