How to set and access values of nested array objects in React state using useState hook?

484 Views Asked by At

This is my state.

const [poll, setPoll] = useState({
    pollQuestion: "Sample question- Is it fine?",
    pollOption: [
      { optionId: 1, optionText: "sample option1", votes: "0" },
      { optionId: 2, optionText: "sample option2", votes: "0" },
      { optionId: 3, optionText: "sample option3", votes: "0" },
      { optionId: 4, optionText: "sample option4", votes: "0" },
    ]
  });

I am trying to set optionText for my poll. I am currently using this, but this is wrong.

onChange={(e) => setPoll({ ...poll, pollOption.optionText: e.target.value })}

Can someone correct me?

Also how to set the value of the option text box?

 value={poll.pollOption.optionText}

I tried this, but it sets the value of all 4 input fields simultaneously

1

There are 1 best solutions below

3
On

You haven't specified what is wrong, but at a first glance, PollOption is an array of objects, so you have to specify the index to access the correct object.

To change the OptionText of the object with index i, try:

onChange={(e) => setPoll({ ...poll, PollOption[i].OptionText: e.target.value })}

So changing the object with OptionId: 4 would mean changing the 4th object in the array, so i = 3:

onChange={(e) => setPoll({ ...poll, PollOption[3].OptionText: e.target.value })}