Home > Software design >  How to push to an array in useState with multiple field in array element
How to push to an array in useState with multiple field in array element

Time:06-30

const[data, setDate] = useState({
  field1 : [{
     f1: "",
     f2: "",
  }],
  field2: [{
     f3: "",
     f4: "",
  }]
})

In the above how I can update and push new element to field1 and field2

CodePudding user response:

You may try the following:

let temp={...data};
temp.field1.push(...);
temp.field2.push(...);

setDate(temp);

CodePudding user response:

const [data, setDate] = useState({
    field1: [
      {
        f1: "",
        f2: ""
      }
    ],
    field2: [
      {
        f3: "",
        f4: ""
      }
    ]
  });
  useEffect(() => {
    let temp = { ...data };
    temp.field1.push({ f3: "" });
    setDate(temp);
  }, []);
  • Related