I am working in react on an Exam app. I have two arrays one with the user's given answers and one with correct answers. Comparing them is not showing the correct results. I am using hooks and the code is inside the useEffect hook. The result is also not showing the correct number of questions.
questions = [
{Qid: 1, Question: "This is question 1",
Answers:[{Ans1:"Answer1",IsCorrect:true}
{Ans2:"Answer2",IsCorrect:false}
{Ans3:"Answer3",IsCorrect:false}
{Ans4:"Answer4",IsCorrect:false}]},
{Qid: 2, Question: "This is question 2",
Answers:[{Ans1:"Answer1",IsCorrect:false}
{Ans2:"Answer2",IsCorrect:true}
{Ans3:"Answer3",IsCorrect:false}
{Ans4:"Answer4",IsCorrect:false}]},
{Qid: 3, Question: "This is question 3",
Answers:[{Ans1:"Answer1",IsCorrect:true}
{Ans2:"Answer2",IsCorrect:false}
{Ans3:"Answer3",IsCorrect:false}
{Ans4:"Answer4",IsCorrect:false}]},
{Qid: 4, Question: "This is question 4",
Answers:[{Ans1:"Answer1",IsCorrect:false}
{Ans2:"Answer2",IsCorrect:false}
{Ans3:"Answer3",IsCorrect:true}
{Ans4:"Answer4",IsCorrect:false}]}
]
keyquestions = [
{Qid: 1, Question: "This is question 1",
Answers:[{Ans1:"Answer1",IsCorrect:false}
{Ans2:"Answer2",IsCorrect:true}
{Ans3:"Answer3",IsCorrect:false}
{Ans4:"Answer4",IsCorrect:false}]},
{Qid: 2, Question: "This is question 2",
Answers:[{Ans1:"Answer1",IsCorrect:false}
{Ans2:"Answer2",IsCorrect:true}
{Ans3:"Answer3",IsCorrect:false}
{Ans4:"Answer4",IsCorrect:false}]},
{Qid: 3, Question: "This is question 3",
Answers:[{Ans1:"Answer1",IsCorrect:true}
{Ans2:"Answer2",IsCorrect:false}
{Ans3:"Answer3",IsCorrect:false}
{Ans4:"Answer4",IsCorrect:false}]},
{Qid: 4, Question: "This is question 4",
Answers:[{Ans1:"Answer1",IsCorrect:false}
{Ans2:"Answer2",IsCorrect:true}
{Ans3:"Answer3",IsCorrect:false}
{Ans4:"Answer4",IsCorrect:false}]}
]
I am using react hooks and the code of the component is
const Results = (props) => {
const [questions, setQuestions] = useState(props.quest);
const [keyq, setKey] = useState(props.keyq);
const [correctAnswers, setCorAns] = useState(0);
const [wrongAnswers, setWrong] = useState(0);
const [once, setOnce] = useState(true);
useEffect(() => {
if(once){
for (let index = 0; index < questions.length; index++) {
var qa = questions[index].Answers;
var ka = keyq[index].Answers;
var k = JSON.stringify(ka);
var q = JSON.stringify(qa);
if (k === q) {
var cor = correctAnswers;
cor = cor + 1;
setCorAns(cor)
} else {
var wr = wrongAnswers;
wr = wr + 1;
setWrong(wr + 1)
}
}
}
setOnce(false);
},[correctAnswers,keyq,questions,wrongAnswers,once])
return (
<div>
<h4>Right: {correctAnswers}</h4>
<h4>Wrong: {wrongAnswers}</h4>
</div>
)
}
export default Results