Made it so the code remembers the user's previous answers to current exercises

This commit is contained in:
Tiago Ribeiro
2023-06-20 17:07:54 +01:00
parent dd357d991c
commit 3a7c29de56
11 changed files with 147 additions and 66 deletions

View File

@@ -47,25 +47,25 @@ function Question({
);
}
export default function MultipleChoice({id, prompt, type, questions, onNext, onBack}: MultipleChoiceExercise & CommonProps) {
const [userSolutions, setUserSolutions] = useState<{question: string; option: string}[]>([]);
export default function MultipleChoice({id, prompt, type, questions, userSolutions, onNext, onBack}: MultipleChoiceExercise & CommonProps) {
const [answers, setAnswers] = useState<{question: string; option: string}[]>(userSolutions);
const [questionIndex, setQuestionIndex] = useState(0);
const onSelectOption = (option: string) => {
const question = questions[questionIndex];
setUserSolutions((prev) => [...prev.filter((x) => x.question !== question.id), {option, question: question.id}]);
setAnswers((prev) => [...prev.filter((x) => x.question !== question.id), {option, question: question.id}]);
};
const calculateScore = () => {
const total = questions.length;
const correct = userSolutions.filter((x) => questions.find((y) => y.id === x.question)?.solution === x.option || false).length;
const correct = answers.filter((x) => questions.find((y) => y.id === x.question)?.solution === x.option || false).length;
return {total, correct};
};
const next = () => {
if (questionIndex === questions.length - 1) {
onNext({exercise: id, solutions: userSolutions, score: calculateScore(), type});
onNext({exercise: id, solutions: answers, score: calculateScore(), type});
} else {
setQuestionIndex((prev) => prev + 1);
}
@@ -73,7 +73,7 @@ export default function MultipleChoice({id, prompt, type, questions, onNext, onB
const back = () => {
if (questionIndex === 0) {
onBack();
onBack({exercise: id, solutions: answers, score: calculateScore(), type});
} else {
setQuestionIndex((prev) => prev - 1);
}
@@ -86,7 +86,7 @@ export default function MultipleChoice({id, prompt, type, questions, onNext, onB
{questionIndex < questions.length && (
<Question
{...questions[questionIndex]}
userSolution={userSolutions.find((x) => questions[questionIndex].id === x.question)?.option}
userSolution={answers.find((x) => questions[questionIndex].id === x.question)?.option}
onSelectOption={onSelectOption}
/>
)}