0

I want to update age array

  const [varient, setVarient] = useState([
    { id: 0, targets: { ageGender: { age: [], gender: [] }, parameterData } },
  ]);

After updating

Result

Array = [
    { id: 0, targets: { ageGender: { age: [12,13], gender: [] }, parameterData } },
  ]
  • 1
    Does this answer your question? [How to update nested state properties in React](https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react) – Emile Bergeron Aug 21 '22 at 22:49

2 Answers2

1

If you want to update your state and the new value is computed based on the previous 'snapshot' (e.g. value) of your state, then you can pass a function to setState. This function takes in the previous snapshot and returns an updated value. This is the recommended approach by the React team. Read more about this concept in the documentation under subheading 'Functional updates'.

I have added a working codesandbox example to answer your question.

JnsBne
  • 121
  • 6
-1

You could do something like this:

 const addAge = (age: number) => {
    const newVarient = [...varient];
    newVarient[0].targets.ageGender.age.push(age);
    setVarient(newVarient);
  }
PCDSandwichMan
  • 1,964
  • 1
  • 12
  • 23