I am making a quiz app and have the following issue - I have a set of questions and answers in an api array. The question is appearing fine from the below code, however the incorrect and correct answers, which appear separately need to be joined together so I can iterate them as multiple choice answers.
In the below the {incorrect_answers} in the h4 wrapper shows the correct answer twice in the list as well as the incorrect answers. How can I make it so that the correct answer only appears once? Please help!
const FirstRound = ({quizArray, setQuizArray, num, setNum}) => {
const {question, id, correct_answer, incorrect_answers} = quizArray[num];
const randNum = Math.round(Math.random() * incorrect_answers.length)+1;
incorrect_answers.splice(randNum, 0, correct_answer)
return <>
<div class="box">
<h1>Quiz Round One</h1>
<h3>{question}</h3>
<h4>{incorrect_answers}</h4>
</div>
<button onClick={Change}>Next</button>
</>
}
This part is suspicious:
const {question, id, correct_answer, incorrect_answers} = quizArray[num];
const randNum = Math.round(Math.random() * incorrect_answers.length)+1;
incorrect_answers.splice(randNum, 0, correct_answer)
It's hard to tell without knowing what the types or values of correct_answer and incorrect_answers are ; however, I suggest adding console.log before and after the incorrect_answers.splice(randNum, 0, correct_answer) line, and see what happens if the component is rendered multiple times.
Since splice mutates Arrays in place, it's possible that you keep modifying the same incorrect_answers list (to add the correct_answer at each rendering.)
You might need to clone the Array first, or use slice instead.