0

I have an JSON array:

1

function createData(nom, age, poids, ) {
  return {
    nom,
    age,
    poids,

  };
}

const [count, setCount] = useState([
  ]);
  
  
  setCount(count=>count.concat(createData("mathieu",15)))
  setCount(count=>count.concat(createData("jean",25)))
  setCount(count=>count.concat(createData("ginette",55)))




  setCount(count=>count[0].poids=13) // doesn't work

I'm trying to add poids=13 in a existing json array when nom= mathieu but doesn't work. Can you help me, I'm new on react hooks. Thanks

Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
Kevin
  • 11
  • 1
  • 1
    Can you please clarify "doesn't work"? That could mean anything. You get an error? Unexpected output? – tnw Aug 18 '20 at 14:32

1 Answers1

2

Your setCount() callback should return the new value of the state. count[0].poids = 13 will return 13. You should also not modify state directly, although your using setState, you're retrieving the previous state and trying to update it directly.

Instead, you can use .map() to return a new array of objects, which will be your new state. Within the .map() callback you can specify how each of your objects "transforms"/changes. If the nom is "mathieu" you can return a newly transformed object, otherwise, you can simply just return the current object.

setCount(count => count.map(
  obj => obj.nom === "mathieu" ? {...obj, poids: 13} : obj
));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64