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

Time:11-16

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

CodePudding user response:

try this the minor change "subject =" to "subject :"

const [count, setCount] = useState(0);
      const [details, setDetails] = useState({
        Name: "saqib",
        Number: null,
        subject: [
          {
            subject1: "1",
            subject2: "2",
          },
        ],
      });

Try This to access the object

{details.name}

{details.subject[0].subject1}

CodePudding user response:

Here is a generic method that handles multiple elements inside the subjects array

  {
    details.subject.map((obj,index) => {
      return Object.entries(obj).map(k => {
        return <input type="text" value={k[1]} onChange={(e) => setDetails({ ...details, subject: Object.assign([ ...details.subject], { [index]: {...details.subject[index], [k[0]]: e.target.value }}) })} />
      })
    })
  }

demo

CodePudding user response:

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.

  • Related