Home > Software engineering >  how to update nested object of array in useState hook in react?
how to update nested object of array in useState hook in react?

Time:12-09

I have a component that has nested objects in array:

  const [documentObj, setDocument] = useState({
    document_name: "",
    form_values: [
      {
        field_seq: null,
        is_mandatory: false,
        field_type: null,
        field_name: "",
        select_values: [
          {
            value: false,
            label: "",
          },
        ],
      },
    ],
  });

I'm trying to update the object properties, but when I try to update the object, it is saying can not reay properties [0]

this is how I'm updating it:


<Form.Control
 type="number"
 value={documentObj.form_values[0].field_seq}
 onChange={(event) => {
  setDocument((prevStyle) => ({
  ...prevStyle,
form_values: [
{
...prevStyle.form_values,
field_seq: event.target.value,
},
],
}));
}}
/>
</Form.Group>

Probably i need to write a function to handle all input value and need some help

CodePudding user response:

Update

While not specified in the post, if Form.Control is from react-bootstrap, according to their doc the value property need to be string | arrayOf | number.

Perhaps also try set an empty string "" as the initial value of field_seq, so this component is fully controlled:

const [documentObj, setDocument] = useState({
  document_name: "",
  form_values: [
    {
      //            
  • Related