reactjsarraysreact-hooksarrayofarrays

In useState hook, i have an object and an array of object. I dont know how to access them


The state variables are -

const [details, setDetails] = useState({
  Name: "",
  Number: null,
  subject= [{
    subject1 : "",
    subject2 : ""
  }]
})


<input type="text" placeholder="Enter name" value={details.Name} onChange={(e) => setDetails({ ...details, Name: e.target.value })} />
<input type="text" placeholder="Enter number" value={details.Number} onChange={(e) => setDetails({ ...details, Number: e.target.value })} />

I dont know how to write access the subjects respectively


Solution

  • Assuming you only want to change the first object of the array in this case, it would look like this:

    <input
      type="text"
      placeholder="Enter subject1"
      value={details.subject[0].subject1}
      onChange={(e) =>
        setDetails((curr) => ({
          ...curr,
          subject: [
            { ...curr.subject[0], subject1: e.target.value },
            ...curr.subject,
          ],
        }))
      }
    />
    <input
      type="text"
      placeholder="Enter subject2"
      value={details.subject[0].subject2}
      onChange={(e) =>
        setDetails((curr) => ({
          ...curr,
          subject: [
            { ...curr.subject[0], subject2: e.target.value },
            ...curr.subject,
          ],
        }))
      }
    />
    

    Please note that the curr callback is to use the current state. This is better than using the details state, since it is set async.