0

i want to create a program like a quiz. the scenario is the user will submit the answer and the answer will be store in array. the variable array is answer.

this.state = { answer : [] }

the user will be give the answer and store to answer. maybe value will be like ['a','b','c'] this is just an example answer will be store in array. Nah, the feature the quiz can show the previous or next question, and the user can change the answer on the array. How to change the value in array in the specific index? In example the answer b in the second index on array will be change to a. How can i change the value?

  • [enter link description here](https://stackoverflow.com/questions/29537299/react-how-to-update-state-item1-in-state-using-setstate) Already Answered Here – Deepanshu May 30 '20 at 04:25

1 Answers1

0
// Use react setState callback to ensure you get the updated state value
this.setState((state) => {
  // Create new array to prevent passing reference to make it pure
  const newAnswer = [...state.answer]
  // Chage value of new array
  newAnswer[index] = newValue

  return {answer: newAnswer}
 }
)
Dev Friend
  • 56
  • 1
  • 7
  • thank for helping this is great answer for me, but i want to ask another question. when the array value is not yet inserted. can i push a value to the specific index from array? – Shyfa Andiantono May 30 '20 at 04:50
  • Yes, you can do that in javascript. But I don't suggest you do that. If you need to access by index you should probably use and object. – Dev Friend May 30 '20 at 04:53