From 72b498eb85f456de92d83fbe5a10a72e3705b424 Mon Sep 17 00:00:00 2001 From: Carlos Mesquita Date: Tue, 27 Aug 2024 09:20:00 +0100 Subject: [PATCH] Fixed a bug in fill blanks where the input would be reset by the re-rendering of lines --- src/components/Exercises/FillBlanks/index.tsx | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/src/components/Exercises/FillBlanks/index.tsx b/src/components/Exercises/FillBlanks/index.tsx index 909860c9..a00c3bb2 100644 --- a/src/components/Exercises/FillBlanks/index.tsx +++ b/src/components/Exercises/FillBlanks/index.tsx @@ -1,7 +1,7 @@ import { FillBlanksExercise, FillBlanksMCOption } from "@/interfaces/exam"; import useExamStore from "@/stores/examStore"; import clsx from "clsx"; -import { Fragment, useEffect, useState } from "react"; +import { Fragment, useCallback, useEffect, useMemo, useState } from "react"; import reactStringReplace from "react-string-replace"; import { CommonProps } from ".."; import Button from "../../Low/Button"; @@ -45,7 +45,7 @@ const FillBlanks: React.FC = ({ let correctWords: any; - if (exam && exam.module === "level" && exam.parts[partIndex].exercises[exerciseIndex].type === "fillBlanks") { + if (exam && (exam.module === "level" || exam.module === "reading") && exam.parts[partIndex].exercises[exerciseIndex].type === "fillBlanks") { correctWords = (exam.parts[partIndex].exercises[exerciseIndex] as FillBlanksExercise).words; } @@ -77,7 +77,7 @@ const FillBlanks: React.FC = ({ const missing = total - answers!.filter((x) => solutions.find((y) => x.id.toString() === y.id.toString())).length; return { total, correct, missing }; }; - const renderLines = (line: string) => { + const renderLines = useCallback((line: string) => { return (
{reactStringReplace(line, /({{\d+}})/g, (match) => { @@ -121,21 +121,33 @@ const FillBlanks: React.FC = ({ })}
); - }; + }, [variant, words, setCurrentMCSelection, answers]); + + const memoizedLines = useMemo(() => { + return text.split("\\n").map((line, index) => ( +

+ {renderLines(line)} +
+

+ )); + }, [text, variant, renderLines]); + const onSelection = (questionID: string, value: string) => { setAnswers((prev) => [...prev.filter((x) => x.id !== questionID), { id: questionID, solution: value }]); } useEffect(() => { - setCurrentSolution({ exercise: id, solutions: answers, score: calculateScore(), type, shuffleMaps: shuffleMaps }); + if (variant === "mc") { + setCurrentSolution({ exercise: id, solutions: answers, score: calculateScore(), type, shuffleMaps: shuffleMaps }); + } // eslint-disable-next-line react-hooks/exhaustive-deps }, [answers]) return ( <>
- {false && + {variant !== "mc" && {prompt.split("\\n").map((line, index) => ( {line} @@ -144,12 +156,7 @@ const FillBlanks: React.FC = ({ ))} } - {text.split("\\n").map((line, index) => ( -

- {renderLines(line)} -
-

- ))} + {memoizedLines}
{variant === "mc" && typeCheckWordsMC(words) ? ( <>