0

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

  • For the first one, which one do you need to change? The entire PollOption? – Veno Sep 30 '20 at 13:11
  • Does this answer your question? [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Adam Jenkins Sep 30 '20 at 13:13
  • @Veno There are 4 similar input fields for entering 4 options. I wanted to change the first object in the PollOption[] array in the state when the user types in the 1st option box. Similarly there will be 3 more onChange functions for the other 3 input fields – Lijo M Loyid Sep 30 '20 at 16:15

1 Answers1

0

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 })}
  • What if the OP wanted to change the second option? What about the one with `optionId` 4? – Adam Jenkins Sep 30 '20 at 13:21
  • Edited my answer with a general and a specific example. – wesley.buijsman Sep 30 '20 at 14:18
  • Thanks @wesley.buijsman for answering, but this doesn't seem to work with useState. I tried the functional way of setting state also by passing previousState and returning a new state, but they are not working. I am attaching a link, you can edit the code live and see https://codesandbox.io/s/nested-objects-doubt-rcu0e – Lijo M Loyid Oct 01 '20 at 10:05