-1

let say I got a state like this

const [peoples, setPeople] = useState[
      {name: 'Sam', power: 0},
      {name: 'Tam', power: 0},
      {name: 'Lam', power: 0},
      {name: 'Bam', power: 0},
      {name: 'Jam', power: 0},
      {name: 'Yum', power: 0},
    ];

For example I wanna update the Bam power to 2, What is the correct way to update this kind of object array

Kerry
  • 384
  • 3
  • 25
  • You would map (i.e. shallow copy) the previous state to the next state since your state is an array, and also shallow copy the element object you want to update. What have you tried already on your own? See [Minimal, Complete, and Reproducible Code Example](https://stackoverflow.com/help/minimal-reproducible-example). – Drew Reese Mar 23 '21 at 04:12
  • It's ok to share your implementation with splice or whatever you have. Using splice would be incorrect since it mutates the array it operates over. – Drew Reese Mar 23 '21 at 04:19
  • You can use `array#map` and then update the value of power. Since it will not mutate your array. – Hassan Imam Mar 23 '21 at 04:20
  • use `useState()` instead of `useState[]`. Also see [React Hooks useState() with Object](https://stackoverflow.com/questions/54150783/react-hooks-usestate-with-object) – Shivam Jha Mar 23 '21 at 04:48

1 Answers1

0

How to setState for the following object array in react

const [peoples, setPeople] = useState([
  {name: 'Sam', power: 0},
  {name: 'Tam', power: 0},
  {name: 'Lam', power: 0},
  {name: 'Bam', power: 0},
  {name: 'Jam', power: 0},
  {name: 'Yum', power: 0},
]); 

const powerUp = (name, power) => {
    setPeople(peoples.map(
        (people) => 
            people.name === name ? {...people, power: power} : people
    ));
};
Jayani Sumudini
  • 1,409
  • 2
  • 22
  • 29
cccjaccck
  • 46
  • 3