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 ...