generated from muhtadeetaron/nextjs-template
fix(exam): fix pretest screen start exam button
This commit is contained in:
@ -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,85 +68,77 @@ 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,
|
||||
]);
|
||||
|
||||
const fetchQuestions = async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/mock/${id}`, {
|
||||
method: "GET",
|
||||
});
|
||||
const data = await response.json();
|
||||
setQuestions(data.questions);
|
||||
} catch (error) {
|
||||
console.error("Error fetching questions:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Fetch questions
|
||||
useEffect(() => {
|
||||
const fetchQuestions = async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/mock/${id}`);
|
||||
const data = await response.json();
|
||||
setQuestions(data.questions);
|
||||
} catch (error) {
|
||||
console.error("Error fetching questions:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
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;
|
||||
return acc;
|
||||
}, {} as Record<number, string>);
|
||||
|
||||
const payload = {
|
||||
mock_id: id,
|
||||
data: answersForAPI,
|
||||
};
|
||||
const answersForAPI = currentAttempt.answers.reduce(
|
||||
(acc, { questionId, answer }) => {
|
||||
acc[+questionId] = answer;
|
||||
return acc;
|
||||
},
|
||||
{} 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,12 +194,10 @@ 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="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 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>
|
||||
);
|
||||
@ -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}
|
||||
/>
|
||||
))}
|
||||
|
||||
Reference in New Issue
Block a user