generated from muhtadeetaron/nextjs-template
fix(exam): fix pretest screen start exam button
This commit is contained in:
@ -32,7 +32,6 @@ export default function PaperScreen() {
|
||||
method: "GET",
|
||||
});
|
||||
const fetchedQuestionData: Mock[] = await questionResponse.json();
|
||||
console.log(fetchedQuestionData[0]?.id);
|
||||
setQuestions(fetchedQuestionData);
|
||||
} catch (error) {
|
||||
setErrorMsg(error instanceof Error ? error.message : "An error occurred");
|
||||
@ -93,6 +92,8 @@ export default function PaperScreen() {
|
||||
displayTabTitle={null}
|
||||
displayUser={false}
|
||||
displaySubject={name}
|
||||
image={undefined}
|
||||
examDuration={undefined}
|
||||
/>
|
||||
<div className="mx-10 pt-10 overflow-y-auto">
|
||||
<div className="border border-[#c0dafc] flex flex-col gap-4 w-full rounded-[25px] p-4">
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useParams, useRouter, useSearchParams } from "next/navigation";
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import { useParams, useRouter, useSearchParams } from "next/navigation";
|
||||
import { useTimer } from "@/context/TimerContext";
|
||||
import { useExam } from "@/context/ExamContext";
|
||||
import { API_URL, getToken } from "@/lib/auth";
|
||||
@ -16,11 +16,10 @@ interface Question {
|
||||
|
||||
interface QuestionItemProps {
|
||||
question: Question;
|
||||
selectedAnswer: string | undefined;
|
||||
selectedAnswer?: string;
|
||||
handleSelect: (questionId: number, option: string) => void;
|
||||
}
|
||||
|
||||
// Components
|
||||
const QuestionItem = React.memo<QuestionItemProps>(
|
||||
({ question, selectedAnswer, handleSelect }) => (
|
||||
<div className="border border-[#8abdff]/50 rounded-2xl p-4">
|
||||
@ -55,16 +54,10 @@ QuestionItem.displayName = "QuestionItem";
|
||||
|
||||
export default function ExamPage() {
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
const searchParams = useSearchParams();
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const id = params.id as string;
|
||||
const time = searchParams.get("time");
|
||||
const { id } = useParams();
|
||||
const time = useSearchParams().get("time");
|
||||
|
||||
const { setInitialTime, stopTimer } = useTimer();
|
||||
|
||||
// Use exam context instead of local state
|
||||
const {
|
||||
currentAttempt,
|
||||
setAnswer,
|
||||
@ -75,41 +68,44 @@ export default function ExamPage() {
|
||||
isExamCompleted,
|
||||
isHydrated,
|
||||
isInitialized,
|
||||
currentExam,
|
||||
} = useExam();
|
||||
|
||||
const [questions, setQuestions] = useState<Question[] | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [submissionLoading, setSubmissionLoading] = useState(false);
|
||||
|
||||
// Check if exam is properly started
|
||||
useEffect(() => {
|
||||
if (!isHydrated) return;
|
||||
if (!isInitialized) return;
|
||||
if (isSubmitting) return; // Don't redirect while submitting
|
||||
console.log(
|
||||
"hydrated:",
|
||||
isHydrated,
|
||||
"initialized:",
|
||||
isInitialized,
|
||||
"exam:",
|
||||
currentExam
|
||||
);
|
||||
}, [isHydrated, isInitialized, currentExam]);
|
||||
|
||||
if (!isExamStarted()) {
|
||||
router.push("/unit");
|
||||
return;
|
||||
}
|
||||
|
||||
if (isExamCompleted()) {
|
||||
router.push("/exam/results");
|
||||
return;
|
||||
}
|
||||
// Initial checks
|
||||
useEffect(() => {
|
||||
if (!isHydrated || !isInitialized || isSubmitting) return;
|
||||
if (!isExamStarted()) return router.push("/unit");
|
||||
if (isExamCompleted()) return router.push("/exam/results");
|
||||
}, [
|
||||
isHydrated,
|
||||
isInitialized,
|
||||
isExamStarted,
|
||||
isExamCompleted,
|
||||
router,
|
||||
isInitialized,
|
||||
isSubmitting,
|
||||
router,
|
||||
]);
|
||||
|
||||
// Fetch questions
|
||||
useEffect(() => {
|
||||
const fetchQuestions = async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/mock/${id}`, {
|
||||
method: "GET",
|
||||
});
|
||||
const response = await fetch(`${API_URL}/mock/${id}`);
|
||||
const data = await response.json();
|
||||
setQuestions(data.questions);
|
||||
} catch (error) {
|
||||
@ -118,42 +114,31 @@ export default function ExamPage() {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchQuestions();
|
||||
if (time) {
|
||||
setInitialTime(Number(time));
|
||||
}
|
||||
if (time) setInitialTime(Number(time));
|
||||
}, [id, time, setInitialTime]);
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(questionId: number, option: string) => {
|
||||
// Store answer in context instead of local reducer
|
||||
setAnswer(questionId.toString(), option);
|
||||
},
|
||||
[setAnswer]
|
||||
);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!currentAttempt) {
|
||||
console.error("No exam attempt found");
|
||||
return;
|
||||
}
|
||||
if (!currentAttempt) return console.error("No exam attempt found");
|
||||
|
||||
stopTimer();
|
||||
setSubmissionLoading(true);
|
||||
setIsSubmitting(true); // Add this line
|
||||
setIsSubmitting(true);
|
||||
|
||||
// Convert context answers to the format your API expects
|
||||
const answersForAPI = currentAttempt.answers.reduce((acc, answer) => {
|
||||
acc[parseInt(answer.questionId)] = answer.answer;
|
||||
const answersForAPI = currentAttempt.answers.reduce(
|
||||
(acc, { questionId, answer }) => {
|
||||
acc[+questionId] = answer;
|
||||
return acc;
|
||||
}, {} as Record<number, string>);
|
||||
|
||||
const payload = {
|
||||
mock_id: id,
|
||||
data: answersForAPI,
|
||||
};
|
||||
},
|
||||
{} as Record<number, string>
|
||||
);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/submit`, {
|
||||
@ -162,33 +147,19 @@ export default function ExamPage() {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${await getToken()}`,
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
body: JSON.stringify({ mock_id: id, data: answersForAPI }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
console.error(
|
||||
"Submission failed:",
|
||||
errorData.message || "Unknown error"
|
||||
);
|
||||
setIsSubmitting(false); // Reset on error
|
||||
return;
|
||||
}
|
||||
if (!response.ok)
|
||||
throw new Error((await response.json()).message || "Submission failed");
|
||||
|
||||
const responseData = await response.json();
|
||||
|
||||
// Submit exam in context (this will store the completed attempt)
|
||||
const completedAttempt = submitExamContext();
|
||||
|
||||
// Store API response in context for results page
|
||||
submitExamContext();
|
||||
setApiResponse(responseData);
|
||||
|
||||
// Navigate to results without URL parameters
|
||||
router.push("/exam/results");
|
||||
console.log("I'm here");
|
||||
} catch (error) {
|
||||
console.error("Error submitting answers:", error);
|
||||
setIsSubmitting(false); // Reset on error
|
||||
setIsSubmitting(false);
|
||||
} finally {
|
||||
setSubmissionLoading(false);
|
||||
}
|
||||
@ -201,12 +172,10 @@ export default function ExamPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// Handle browser back button
|
||||
useEffect(() => {
|
||||
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
|
||||
e.preventDefault();
|
||||
e.returnValue = "";
|
||||
return "";
|
||||
};
|
||||
|
||||
const handlePopState = (e: PopStateEvent) => {
|
||||
@ -225,14 +194,12 @@ export default function ExamPage() {
|
||||
|
||||
if (submissionLoading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="flex flex-col items-center justify-center min-h-64">
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-900 mb-4"></div>
|
||||
<p className="text-lg font-medium text-gray-900">Submitting...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -252,11 +219,11 @@ export default function ExamPage() {
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-6 mb-20">
|
||||
{questions?.map((question) => (
|
||||
{questions?.map((q) => (
|
||||
<QuestionItem
|
||||
key={question.id}
|
||||
question={question}
|
||||
selectedAnswer={getAnswer(question.id.toString())}
|
||||
key={q.id}
|
||||
question={q}
|
||||
selectedAnswer={getAnswer(q.id.toString())}
|
||||
handleSelect={handleSelect}
|
||||
/>
|
||||
))}
|
||||
|
||||
@ -7,6 +7,7 @@ import DestructibleAlert from "@/components/DestructibleAlert";
|
||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||
import { API_URL } from "@/lib/auth";
|
||||
import { useExam } from "@/context/ExamContext";
|
||||
import { Exam } from "@/types/exam";
|
||||
|
||||
interface Metadata {
|
||||
metadata: {
|
||||
@ -20,7 +21,7 @@ interface Metadata {
|
||||
export default function PretestPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const [examData, setExamData] = useState();
|
||||
const [examData, setExamData] = useState<Exam>();
|
||||
const { startExam, setCurrentExam } = useExam();
|
||||
|
||||
// Get params from URL search params
|
||||
@ -41,14 +42,13 @@ export default function PretestPage() {
|
||||
const questionResponse = await fetch(`${API_URL}/mock/${id}`, {
|
||||
method: "GET",
|
||||
});
|
||||
const data = await questionResponse.json();
|
||||
console.log(data);
|
||||
|
||||
if (!questionResponse.ok) {
|
||||
throw new Error("Failed to fetch questions");
|
||||
}
|
||||
setExamData(data);
|
||||
const data = await questionResponse.json();
|
||||
const fetchedMetadata: Metadata = data;
|
||||
|
||||
setExamData(data);
|
||||
setMetadata(fetchedMetadata);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
@ -79,6 +79,25 @@ export default function PretestPage() {
|
||||
</BackgroundWrapper>
|
||||
);
|
||||
}
|
||||
const { isHydrated, isInitialized, currentExam } = useExam();
|
||||
|
||||
useEffect(() => {
|
||||
console.log(
|
||||
"hydrated:",
|
||||
isHydrated,
|
||||
"initialized:",
|
||||
isInitialized,
|
||||
"exam:",
|
||||
currentExam
|
||||
);
|
||||
}, [isHydrated, isInitialized, currentExam]);
|
||||
|
||||
function handleStartExam() {
|
||||
console.log(id);
|
||||
setCurrentExam(examData);
|
||||
startExam();
|
||||
router.push(`/exam/${id}?time=${metadata?.metadata.duration}`);
|
||||
}
|
||||
|
||||
return (
|
||||
<BackgroundWrapper>
|
||||
@ -176,11 +195,7 @@ export default function PretestPage() {
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
setCurrentExam(examData); // Set exam first
|
||||
startExam(); // Then start exam
|
||||
router.push(`/exam/${id}?time=${metadata.metadata.duration}`);
|
||||
}}
|
||||
onClick={async () => handleStartExam()}
|
||||
className="fixed bottom-0 w-full bg-[#113768] h-[78px] justify-center items-center flex text-white text-2xl font-bold"
|
||||
>
|
||||
Start Test
|
||||
|
||||
@ -4,6 +4,7 @@ import { useRouter } from "next/navigation";
|
||||
import { useExam, useExamResults } from "@/context/ExamContext";
|
||||
import { useEffect } from "react";
|
||||
import React from "react";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
|
||||
interface Question {
|
||||
solution: string;
|
||||
@ -54,7 +55,7 @@ export default function ResultsPage() {
|
||||
useEffect(() => {
|
||||
// Redirect if no completed exam
|
||||
if (!isExamCompleted()) {
|
||||
router.push("/exam/select");
|
||||
router.push("/unit");
|
||||
return;
|
||||
}
|
||||
}, [isExamCompleted, router]);
|
||||
@ -67,15 +68,10 @@ export default function ResultsPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-4">
|
||||
No exam results found
|
||||
</h1>
|
||||
<button
|
||||
onClick={() => router.push("/exam/select")}
|
||||
className="bg-blue-900 text-white px-6 py-3 rounded-lg hover:bg-blue-800"
|
||||
>
|
||||
Take an Exam
|
||||
</button>
|
||||
<div className="mt-60 flex flex-col items-center">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-4"></div>
|
||||
<p className="text-xl font-medium text-center">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@ -85,8 +81,12 @@ export default function ResultsPage() {
|
||||
const apiResponse = getApiResponse();
|
||||
|
||||
const handleBackToHome = () => {
|
||||
router.push("/unit");
|
||||
clearExam();
|
||||
|
||||
// Give time for state to fully reset before pushing new route
|
||||
setTimeout(() => {
|
||||
router.push("/unit");
|
||||
}, 400); // 50–100ms is usually enough
|
||||
};
|
||||
|
||||
const timeTaken =
|
||||
@ -100,18 +100,24 @@ export default function ResultsPage() {
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-white">
|
||||
<div className="bg-white rounded-lg shadow-lg px-10 py-20">
|
||||
<button className="p-10" onClick={() => router.push("/unit")}>
|
||||
<ArrowLeft size={30} color="black" />
|
||||
</button>
|
||||
<div className="bg-white rounded-lg shadow-lg px-10 pb-20">
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-2 text-center">
|
||||
Keep up the good work!
|
||||
</h1>
|
||||
|
||||
{/* Score Display */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
|
||||
<div className="bg-blue-50 rounded-lg p-6 text-center">
|
||||
<div className="text-3xl font-bold text-blue-900 mb-2">
|
||||
{examResults.score}%
|
||||
<div className="mb-8">
|
||||
<div className="bg-blue-50/60 border border-[#113678]/50 rounded-4xl h-[150px] flex flex-col items-center justify-center">
|
||||
<div className="text-xl text-black mb-2">Accuracy:</div>
|
||||
<div className="text-5xl font-bold text-[#113678]">
|
||||
{((examResults.score / examResults.totalQuestions) * 100).toFixed(
|
||||
1
|
||||
)}
|
||||
%
|
||||
</div>
|
||||
<div className="text-sm text-gray-600">Final Score</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -122,7 +128,11 @@ export default function ResultsPage() {
|
||||
</h3>
|
||||
<div className="flex flex-col gap-7">
|
||||
{apiResponse.questions?.map((question) => (
|
||||
<QuestionItem key={question.id} question={question} />
|
||||
<QuestionItem
|
||||
key={question.id}
|
||||
question={question}
|
||||
selectedAnswer={undefined}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -15,7 +15,7 @@ const montserrat = Montserrat({
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "ExamJam",
|
||||
description: "Your exam preparation platform",
|
||||
description: "The best place to prepare for your exams!",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
|
||||
@ -58,7 +58,7 @@ export default function Home() {
|
||||
{/* Action Buttons */}
|
||||
<div className="flex flex-col gap-4">
|
||||
<button
|
||||
onClick={() => router.push("/login")}
|
||||
onClick={() => router.replace("/login")}
|
||||
className="w-full h-[60px] flex justify-center items-center border border-[#113768] rounded-full bg-transparent hover:bg-[#113768] hover:text-white transition-colors duration-200"
|
||||
>
|
||||
<span
|
||||
|
||||
@ -4,6 +4,7 @@ import Image from "next/image";
|
||||
import { ChevronLeft, Layers } from "lucide-react";
|
||||
import { useTimer } from "@/context/TimerContext";
|
||||
import styles from "@/css/Header.module.css";
|
||||
import { useExam } from "@/context/ExamContext";
|
||||
|
||||
const API_URL = "https://examjam-api.pptx704.com";
|
||||
|
||||
@ -26,6 +27,7 @@ const Header = ({
|
||||
examDuration,
|
||||
}) => {
|
||||
const router = useRouter();
|
||||
const { clearExam } = useExam();
|
||||
const [totalSeconds, setTotalSeconds] = useState(
|
||||
examDuration ? parseInt(examDuration) * 60 : 0
|
||||
);
|
||||
@ -86,6 +88,7 @@ const Header = ({
|
||||
if (stopTimer) {
|
||||
stopTimer();
|
||||
}
|
||||
clearExam();
|
||||
router.push("/unit");
|
||||
}
|
||||
};
|
||||
|
||||
@ -81,7 +81,7 @@ export const ExamProvider: React.FC<{ children: ReactNode }> = ({
|
||||
|
||||
const setCurrentExam = (exam: Exam) => {
|
||||
setCurrentExamState(exam);
|
||||
// Clear any existing attempt when setting a new exam
|
||||
|
||||
setCurrentAttemptState(null);
|
||||
};
|
||||
|
||||
@ -167,6 +167,7 @@ export const ExamProvider: React.FC<{ children: ReactNode }> = ({
|
||||
...currentAttempt,
|
||||
endTime: new Date(),
|
||||
score,
|
||||
totalQuestions,
|
||||
passed: currentAttempt.exam.passingScore
|
||||
? score >= currentAttempt.exam.passingScore
|
||||
: undefined,
|
||||
@ -176,7 +177,7 @@ export const ExamProvider: React.FC<{ children: ReactNode }> = ({
|
||||
return completedAttempt;
|
||||
};
|
||||
|
||||
const clearExam = () => {
|
||||
const clearExam = (): void => {
|
||||
setCurrentExamState(null);
|
||||
setCurrentAttemptState(null);
|
||||
};
|
||||
@ -205,10 +206,7 @@ export const ExamProvider: React.FC<{ children: ReactNode }> = ({
|
||||
return totalQuestions > 0 ? (answeredQuestions / totalQuestions) * 100 : 0;
|
||||
};
|
||||
|
||||
const isExamStarted = (): boolean => {
|
||||
if (!isHydrated) return false; // ⛔ wait for hydration
|
||||
return currentAttempt !== null && !currentAttempt.endTime;
|
||||
};
|
||||
const isExamStarted = () => !!currentExam && !!currentAttempt;
|
||||
|
||||
const isExamCompleted = (): boolean => {
|
||||
if (!isHydrated) return false; // ⛔ wait for hydration
|
||||
|
||||
@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
Before Width: | Height: | Size: 1.3 KiB |
1
types/exam.d.ts
vendored
1
types/exam.d.ts
vendored
@ -29,6 +29,7 @@ export interface ExamAttempt {
|
||||
score?: number;
|
||||
passed?: boolean;
|
||||
apiResponse?: any;
|
||||
totalQuestions: number;
|
||||
}
|
||||
|
||||
export interface ExamContextType {
|
||||
|
||||
Reference in New Issue
Block a user