Home > Software design >  How to update complex nested object in setState?
How to update complex nested object in setState?

Time:06-11

How can I access the index inside array and update it without removing property and value inside the object?

  const [data, setData] = useState({

    commission: [{ commissionFor: "", commissionPercentage: "" }],
    salary: [{ salaryFor: "", salaryPrice: "" }],
    off: [{ offFor: "", offPercentage: "" }],
  });

          <Autocomplete
            onChange={(e, value) =>
              setData((data) => ({
                ...data,
                ["commission"]: {
                  ...data[0],
                  ["commissionFor"]: value || e.target.value,
                },
              }))
            }
            renderInput={(params) => <TextField {...params} label="Commission" />}
          />

CodePudding user response:

Can be done like this

setData((data) => ({
    ...data,
    commission: data.commission.map((c, index) => index === 0 ? {...c, commissionFor: value || e.target.value}: c)
}))

CodePudding user response:

If you are mapping these data then after clicking of data send the index of that item using that index position of the 0

  • Related