Skip to content

Commit

Permalink
fix attemp
Browse files Browse the repository at this point in the history
  • Loading branch information
georgetanyeah committed Sep 9, 2024
1 parent dc667d6 commit 34ce330
Show file tree
Hide file tree
Showing 5 changed files with 115 additions and 15 deletions.
8 changes: 6 additions & 2 deletions app/exam/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import LoadingIndicator from "@azure-fundamentals/components/LoadingIndicator";
const questionsQuery = gql`
query RandomQuestions($range: Int!, $link: String) {
randomQuestions(range: $range, link: $link) {
id
question
options {
isAnswer
Expand All @@ -29,7 +30,7 @@ const questionsQuery = gql`
const Exam: NextPage<{ searchParams: { url: string; name: string } }> = ({
searchParams,
}) => {
const { url } = searchParams;
const { url, name } = searchParams;
const { minutes, seconds } = {
minutes: 15,
seconds: 0,
Expand All @@ -42,7 +43,7 @@ const Exam: NextPage<{ searchParams: { url: string; name: string } }> = ({
const [currentQuestionIndex, setCurrentQuestionIndex] = useState<number>(0);
const [countAnswered, setCountAnswered] = useState<number>(0);
const { data, loading, error } = useQuery(questionsQuery, {
variables: { range: 30, link: url },
variables: { range: 3, link: url },
});
const [resultPoints, setResultPoints] = useState<number>(0);
const [passed, setPassed] = useState<boolean>(false);
Expand All @@ -63,6 +64,7 @@ const Exam: NextPage<{ searchParams: { url: string; name: string } }> = ({
};

const handleNextQuestion = (questionNo: number) => {
console.log("handleNextQuestion", questionNo);
setCurrentQuestionIndex(questionNo);
setCurrentQuestion(data?.randomQuestions[questionNo]);
};
Expand Down Expand Up @@ -135,6 +137,8 @@ const Exam: NextPage<{ searchParams: { url: string; name: string } }> = ({
revealExam={revealExam}
getResultPoints={getResultPoints}
questions={data.randomQuestions}
examName={name}
countAnswered={countAnswered}
hideExam={() => {
setRevealExam(false);
}}
Expand Down
4 changes: 2 additions & 2 deletions components/ExamResult.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const ExamResult: React.FC<Props> = ({
</p>
</div>
</div>
<p className="text-white text-sm sm:text-lg mx-auto sm:w-[490px] text-center mt-5 mb-10 sm:mb-20">
<div className="text-white text-sm sm:text-lg mx-auto sm:w-[490px] text-center mt-5 mb-10 sm:mb-20">
{status ? (
<>
<p>Congratulations!</p>
Expand All @@ -56,7 +56,7 @@ const ExamResult: React.FC<Props> = ({
</p>
</>
)}
</p>
</div>
<div className="flex justify-center flex-col sm:flex-row gap-4">
<Button
type="button"
Expand Down
107 changes: 98 additions & 9 deletions components/QuizExamForm.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { useEffect, useState } from "react";
import { useCallback, useEffect, useState } from "react";
import Image from "next/image";
import { Question } from "./types";
import { Question, Answer } from "./types";
import { FieldArray, FormikProvider, Field, useFormik } from "formik";
import { Button } from "./Button";
import useResults from "@azure-fundamentals/hooks/useResults";
import LoadingIndicator from "./LoadingIndicator";

type Props = {
isLoading: boolean;
handleNextQuestion: (q: number) => void;
Expand All @@ -22,6 +21,8 @@ type Props = {
hideExam?: () => void;
remainingTime?: string;
link: string;
examName: string;
countAnswered: number;
images?: { url: string; alt: string }[];
};

Expand All @@ -42,9 +43,12 @@ const QuizExamForm: React.FC<Props> = ({
remainingTime,
link,
images,
examName,
countAnswered,
}) => {
const [showCorrectAnswer, setShowCorrectAnswer] = useState<boolean>(false);
const [savedAnswers, setSavedAnswers] = useState<any>([]);
const [allAnswers, setAllAnswers] = useState<any[]>([]);
const { points, reCount } = useResults(savedAnswers);
const [selectedImage, setSelectedImage] = useState<{
url: string;
Expand All @@ -65,12 +69,7 @@ const QuizExamForm: React.FC<Props> = ({
],
},
onSubmit: () => {
saveAnswers(false).then(() => {
reCount({
questions: questions,
answers: savedAnswers,
});
});
saveAnswers(false);
stopTimer();
},
});
Expand All @@ -91,6 +90,76 @@ const QuizExamForm: React.FC<Props> = ({
}
}, [remainingTime]);

// Function to save all questions to localStorage, with duplication check
const saveAllQuestions = (allAnswers: Answer[]) => {
// Retrieve existing questions data from local storage
const existingData: Answer[] = JSON.parse(
localStorage.getItem(`${examName}-userQuestions`) || "[]",
);

// Map to easily access existing entries by questionId
const existingMap = new Map(
existingData.map((item) => [item.questionId, item]),
);

// Iterate over allAnswers to update existing entries or add new ones

allAnswers.forEach((answer: Answer) => {
const existingAnswer = existingMap.get(answer.questionId);

if (existingAnswer) {
// If the question already exists, update it
existingAnswer.userSelection = answer.userSelection;
existingAnswer.isIncorrect = answer.isIncorrect;
} else {
// If it doesn't exist, add the new answer
existingMap.set(answer.questionId, answer);
}
});

// Convert the map back to an array for storage
const updatedData = Array.from(existingMap.values());

// Save the updated or new data back to local storage
localStorage.setItem(
`${examName}-userQuestions`,
JSON.stringify(updatedData),
);
};

useEffect(() => {
console.log(
"saveAllQuestions effect, ",
allAnswers,
"countAnswered: ",
countAnswered,
);
if (countAnswered == totalQuestions) {
console.log("effect in, ", allAnswers);
saveAllQuestions(allAnswers);
}
}, [allAnswers]);
useEffect(() => {
console.log(
"reCount effect, ",
allAnswers,
"countAnswered: ",
countAnswered,
);
if (countAnswered == totalQuestions) {
console.log(
"reCount effect in, ",
allAnswers,
"countAnswered: ",
countAnswered,
);
reCount({
questions: questions,
answers: allAnswers,
});
}
}, [savedAnswers]);

const nextQuestion = (skip: boolean) => {
if (skip === false) {
let done = true;
Expand Down Expand Up @@ -172,6 +241,7 @@ const QuizExamForm: React.FC<Props> = ({
}, [options]);

const saveAnswers = async (skip = false) => {
console.log("called");
if (skip === true) {
let saved = [...savedAnswers];
saved[currentQuestionIndex] = null;
Expand All @@ -191,6 +261,25 @@ const QuizExamForm: React.FC<Props> = ({
saved[currentQuestionIndex] =
noOfAnswers > 1 && selectedArr?.length > 0 ? selectedArr : selected;
setSavedAnswers(saved);

// Check if the answer is correct or incorrect
const isCorrect = formik.values.options.every((option: any) => {
return option.isAnswer === option.checked;
});
console.log("setAllAnswers", "called");
// Add all questions to `allAnswers` with correctness information
setAllAnswers((prev) => {
var result = [
...prev,
{
questionId: questions[currentQuestionIndex].id,
question: questions[currentQuestionIndex].question,
userSelection: saved[currentQuestionIndex],
isIncorrect: !isCorrect, // Mark if incorrect
},
];
return result;
});
};

if (isLoading) return <LoadingIndicator />;
Expand Down
7 changes: 7 additions & 0 deletions components/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export type Question = {
id: string;
question: string;
options: Option[];
images: Image[];
Expand All @@ -13,3 +14,9 @@ type Option = {
text: string;
isAnswer: boolean;
};

export type Answer = {
questionId: string;
userSelection: string[] | string;
isIncorrect: boolean;
};
4 changes: 2 additions & 2 deletions lib/graphql/resolvers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ const resolvers = {
{ dataSources }: { dataSources: any },
) => {
const response = await fetchQuestions(link);
const shuffled = response?.sort(() => 0.5 - Math.random());
return shuffled?.slice(0, range);
// const shuffled = response?.sort(() => 0.5 - Math.random());
return response?.slice(0, range);
},
},
};
Expand Down

0 comments on commit 34ce330

Please sign in to comment.