0

I'm making a pretty simple react quiz app in which you go from question to question via a 'next' button. Each time the next button is clicked a useState hook (passed as props to onAnswerUpdate) pushes an object with the question's title and the chosen answer to an array named 'answers':

const nextClickHandler = (e) => {
    if(selected === '') {
      return setError('Please select one option');
    }
    onAnswerUpdate(prevState => [...prevState, { q: data.question, a: selected }]);
    setSelected('');
    if(activeQuestion < numberOfQuestions - 1) {
      onSetActiveQuestion(activeQuestion + 1);
    }else ...
  }

I implemented a basic previous button logic whose only function is to return to the previous question but I struggled to find a way to replace the object in the answers array corresponding to the correct question when I change the answer to an already answered question. I've tried replacing it using the activeQuestion number as an index to the array (like in the code sample below) and splice method but neither of them worked. Any help will be greatly appreciated.

const nextClickHandler = (e) => {
      if(selected === '') {
        return setError('Please select one option');
      }
      onAnswerUpdate(prevState => [...prevState, answers[activeQuestion] = { q: data.question, a: selected }]);
      setSelected('');
      if(activeQuestion < numberOfQuestions - 1) {
        onSetActiveQuestion(activeQuestion + 1);
      } else ...
CapBul
  • 55
  • 1
  • 9
  • It's easier to have a static array of answers, and update the index of the active question when you do next and back - see this question (and answer) - https://stackoverflow.com/questions/59459436/cycle-through-objects-in-an-array-by-setting-state-with-a-button-react/59459617#59459617 – Ori Drori Mar 09 '21 at 16:16

1 Answers1

0

Hook with prevState and an array always drive me crazy... I prefer to use an easier approach. If you need to replace an element inside an array that is on state, you could write:

...
let currAnswer = answer;
currAnswer[activeQuestion] = { q: data.question, a: selected };
onAnswerUpdate(currAnswer);
...
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30