Home > OS >  How to update the array in nested array of objects in react state?
How to update the array in nested array of objects in react state?

Time:08-22

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 } },
  ]

CodePudding user response:

You could do something like this:

 const addAge = (age: number) => {
    const newVarient = [...varient];
    newVarient[0].targets.ageGender.age.push(age);
    setVarient(newVarient);
  }

CodePudding user response:

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.

  • Related