generated from muhtadeetaron/nextjs-template
fix(api): fix api logic for exam screen
needs more work for the timercontext
This commit is contained in:
@ -1,231 +1,100 @@
|
||||
"use client";
|
||||
|
||||
import React, {
|
||||
createContext,
|
||||
useContext,
|
||||
useState,
|
||||
useEffect,
|
||||
ReactNode,
|
||||
} from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import React, { createContext, useContext, useState } from "react";
|
||||
import { Test, Answer } from "@/types/exam";
|
||||
import { API_URL } from "@/lib/auth";
|
||||
import { getToken } from "@/lib/auth";
|
||||
|
||||
import { Test, TestAttempt, TestContextType, Answer } from "@/types/exam";
|
||||
import { getFromStorage, removeFromStorage, setToStorage } from "@/lib/utils";
|
||||
import { useAuth } from "./AuthContext";
|
||||
interface ExamContextType {
|
||||
test: Test | null;
|
||||
answers: Answer[];
|
||||
startExam: (testType: string, testId: string) => Promise<void>;
|
||||
setAnswer: (questionIndex: number, answer: Answer) => void;
|
||||
submitExam: () => Promise<void>;
|
||||
cancelExam: () => void;
|
||||
}
|
||||
|
||||
const ExamContext = createContext<TestContextType | undefined>(undefined);
|
||||
const ExamContext = createContext<ExamContextType | undefined>(undefined);
|
||||
|
||||
const STORAGE_KEYS = {
|
||||
CURRENT_EXAM: "current-exam",
|
||||
CURRENT_ATTEMPT: "current-attempt",
|
||||
} as const;
|
||||
|
||||
export const ExamProvider: React.FC<{ children: ReactNode }> = ({
|
||||
export const ExamProvider: React.FC<{ children: React.ReactNode }> = ({
|
||||
children,
|
||||
}) => {
|
||||
const router = useRouter();
|
||||
const [currentExam, setCurrentExamState] = useState<Test | null>(null);
|
||||
const [currentAttempt, setCurrentAttemptState] = useState<TestAttempt | null>(
|
||||
null
|
||||
);
|
||||
const [isHydrated, setIsHydrated] = useState(false);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
const { user } = useAuth();
|
||||
const [test, setTest] = useState<Test | null>(null);
|
||||
const [answers, setAnswers] = useState<Answer[]>([]);
|
||||
|
||||
// Hydrate from storage
|
||||
useEffect(() => {
|
||||
const savedExam = getFromStorage<Test>(STORAGE_KEYS.CURRENT_EXAM);
|
||||
const savedAttempt = getFromStorage<TestAttempt>(
|
||||
STORAGE_KEYS.CURRENT_ATTEMPT
|
||||
);
|
||||
// start exam
|
||||
const startExam = async (testType: string, testId: string) => {
|
||||
try {
|
||||
const token = await getToken(); // if needed
|
||||
const res = await fetch(`${API_URL}/tests/${testType}/${testId}`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (savedExam) setCurrentExamState(savedExam);
|
||||
if (savedAttempt) setCurrentAttemptState(savedAttempt);
|
||||
|
||||
setIsHydrated(true);
|
||||
}, []);
|
||||
|
||||
// Persist exam
|
||||
useEffect(() => {
|
||||
if (!isHydrated) return;
|
||||
if (currentExam) {
|
||||
setToStorage(STORAGE_KEYS.CURRENT_EXAM, currentExam);
|
||||
} else {
|
||||
removeFromStorage(STORAGE_KEYS.CURRENT_EXAM);
|
||||
if (!res.ok) throw new Error(`Failed to fetch test: ${res.status}`);
|
||||
const data: Test = await res.json();
|
||||
setTest(data);
|
||||
setAnswers(Array(data.questions.length).fill(null));
|
||||
} catch (err) {
|
||||
console.error("startExam error:", err);
|
||||
}
|
||||
}, [currentExam, isHydrated]);
|
||||
|
||||
// Persist attempt
|
||||
useEffect(() => {
|
||||
if (!isHydrated) return;
|
||||
if (currentAttempt) {
|
||||
setToStorage(STORAGE_KEYS.CURRENT_ATTEMPT, currentAttempt);
|
||||
} else {
|
||||
removeFromStorage(STORAGE_KEYS.CURRENT_ATTEMPT);
|
||||
}
|
||||
}, [currentAttempt, isHydrated]);
|
||||
|
||||
const setCurrentExam = (exam: Test) => {
|
||||
setCurrentExamState(exam);
|
||||
setCurrentAttemptState(null);
|
||||
};
|
||||
|
||||
const startExam = (exam?: Test): void => {
|
||||
const examToUse = exam || currentExam;
|
||||
const user_id = user?.user_id;
|
||||
|
||||
if (!examToUse) {
|
||||
console.warn("No exam selected, redirecting to /unit");
|
||||
router.push("/unit");
|
||||
return;
|
||||
}
|
||||
|
||||
const attempt: TestAttempt = {
|
||||
user_id: user_id, // TODO: inject from auth
|
||||
test_id: examToUse.metadata.test_id,
|
||||
subject_id: "temp-subject", // TODO: might delete
|
||||
topic_id: "temp-topic", // TODO: might delete
|
||||
test_type: "Mock", // or "Subject"/"Topic" depending on flow
|
||||
attempt_id: crypto.randomUUID(),
|
||||
start_time: new Date().toISOString(),
|
||||
end_time: "",
|
||||
user_questions: examToUse.questions,
|
||||
user_answers: Array(examToUse.questions.length).fill(null),
|
||||
correct_answers: [],
|
||||
correct_answers_count: 0,
|
||||
wrong_answers_count: 0,
|
||||
skipped_questions_count: 0,
|
||||
};
|
||||
|
||||
setCurrentAttemptState(attempt);
|
||||
setIsInitialized(true);
|
||||
};
|
||||
|
||||
const setAnswer = (questionId: string, answer: Answer) => {
|
||||
if (!currentAttempt) {
|
||||
console.warn("No exam attempt started, redirecting to /unit");
|
||||
router.push("/unit");
|
||||
return;
|
||||
}
|
||||
|
||||
const questionIndex = currentAttempt.user_questions.findIndex(
|
||||
(q) => q.question_id === questionId
|
||||
);
|
||||
if (questionIndex === -1) return;
|
||||
|
||||
setCurrentAttemptState((prev) => {
|
||||
if (!prev) return null;
|
||||
const updatedAnswers = [...prev.user_answers];
|
||||
updatedAnswers[questionIndex] = answer;
|
||||
return { ...prev, user_answers: updatedAnswers };
|
||||
// update answer
|
||||
const setAnswer = (questionIndex: number, answer: Answer) => {
|
||||
setAnswers((prev) => {
|
||||
const updated = [...prev];
|
||||
updated[questionIndex] = answer;
|
||||
return updated;
|
||||
});
|
||||
};
|
||||
|
||||
const setApiResponse = (response: any) => {
|
||||
// If you want to store API response in attempt
|
||||
setCurrentAttemptState((prev) =>
|
||||
prev ? { ...prev, apiResponse: response } : null
|
||||
);
|
||||
};
|
||||
// submit exam
|
||||
const submitExam = async () => {
|
||||
if (!test) return;
|
||||
const token = await getToken();
|
||||
try {
|
||||
const { type, test_id, attempt_id } = test.metadata;
|
||||
const res = await fetch(
|
||||
`${API_URL}/tests/${type}/${test_id}/${attempt_id}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({ answers }),
|
||||
}
|
||||
);
|
||||
if (!res.ok) throw new Error("Failed to submit exam");
|
||||
|
||||
const submitExam = (): TestAttempt | null => {
|
||||
if (!currentAttempt) {
|
||||
console.warn("No exam attempt to submit, redirecting to /unit");
|
||||
router.push("/unit");
|
||||
return null;
|
||||
// clear
|
||||
setTest(null);
|
||||
setAnswers([]);
|
||||
} catch (err) {
|
||||
console.error("Failed to submit exam. Reason:", err);
|
||||
}
|
||||
|
||||
const totalQuestions = currentAttempt.user_questions.length;
|
||||
|
||||
// Example evaluation (assumes correct answers in `correct_answers`)
|
||||
const wrong = currentAttempt.user_answers.filter(
|
||||
(ans, idx) => ans !== null && ans !== currentAttempt.correct_answers[idx]
|
||||
).length;
|
||||
|
||||
const skipped = currentAttempt.user_answers.filter(
|
||||
(ans) => ans === null
|
||||
).length;
|
||||
const correct = totalQuestions - wrong - skipped;
|
||||
|
||||
const completedAttempt: TestAttempt = {
|
||||
...currentAttempt,
|
||||
end_time: new Date().toISOString(),
|
||||
correct_answers_count: correct,
|
||||
wrong_answers_count: wrong,
|
||||
skipped_questions_count: skipped,
|
||||
};
|
||||
|
||||
setCurrentAttemptState(completedAttempt);
|
||||
return completedAttempt;
|
||||
};
|
||||
|
||||
const clearExam = (): void => {
|
||||
setCurrentExamState(null);
|
||||
setCurrentAttemptState(null);
|
||||
};
|
||||
|
||||
const getAnswer = (questionId: string): Answer => {
|
||||
if (!currentAttempt) return null;
|
||||
const index = currentAttempt.user_questions.findIndex(
|
||||
(q) => q.question_id === questionId
|
||||
);
|
||||
return index >= 0 ? currentAttempt.user_answers[index] : null;
|
||||
};
|
||||
|
||||
const getApiResponse = (): any => {
|
||||
return (currentAttempt as any)?.apiResponse;
|
||||
};
|
||||
|
||||
const getProgress = (): number => {
|
||||
if (!currentAttempt) return 0;
|
||||
const totalQuestions = currentAttempt.user_questions.length;
|
||||
const answered = currentAttempt.user_answers.filter(
|
||||
(a) => a !== null
|
||||
).length;
|
||||
return totalQuestions > 0 ? (answered / totalQuestions) * 100 : 0;
|
||||
};
|
||||
|
||||
const isExamStarted = () => !!currentExam && !!currentAttempt;
|
||||
|
||||
const isExamCompleted = (): boolean => {
|
||||
if (!isHydrated) return false;
|
||||
return !!currentAttempt?.end_time;
|
||||
};
|
||||
|
||||
const contextValue: TestContextType = {
|
||||
currentExam,
|
||||
currentAttempt,
|
||||
setCurrentExam,
|
||||
startExam,
|
||||
setAnswer,
|
||||
submitExam,
|
||||
clearExam,
|
||||
setApiResponse,
|
||||
getAnswer,
|
||||
getProgress,
|
||||
isExamStarted,
|
||||
isExamCompleted,
|
||||
getApiResponse,
|
||||
isHydrated,
|
||||
isInitialized,
|
||||
// cancel exam
|
||||
const cancelExam = () => {
|
||||
setTest(null);
|
||||
setAnswers([]);
|
||||
};
|
||||
|
||||
return (
|
||||
<ExamContext.Provider value={contextValue}>{children}</ExamContext.Provider>
|
||||
<ExamContext.Provider
|
||||
value={{ test, answers, startExam, setAnswer, submitExam, cancelExam }}
|
||||
>
|
||||
{children}
|
||||
</ExamContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useExam = (): TestContextType => {
|
||||
const context = useContext(ExamContext);
|
||||
if (!context) {
|
||||
throw new Error("useExam must be used within an ExamProvider");
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export const useExamResults = (): TestAttempt | null => {
|
||||
const { currentAttempt, isExamCompleted, isHydrated } = useExam();
|
||||
if (!isHydrated) return null;
|
||||
if (!isExamCompleted() || !currentAttempt) return null;
|
||||
return currentAttempt;
|
||||
export const useExam = (): ExamContextType => {
|
||||
const ctx = useContext(ExamContext);
|
||||
if (!ctx) throw new Error("useExam must be used inside ExamProvider");
|
||||
return ctx;
|
||||
};
|
||||
|
||||
@ -1,31 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect } from "react";
|
||||
import React, {
|
||||
createContext,
|
||||
useContext,
|
||||
useState,
|
||||
useEffect,
|
||||
useRef,
|
||||
} from "react";
|
||||
|
||||
// Define the context type
|
||||
interface TimerContextType {
|
||||
timeRemaining: number;
|
||||
resetTimer: (duration: number) => void;
|
||||
stopTimer: () => void;
|
||||
setInitialTime: (duration: number) => void; // New function to set the initial time
|
||||
setInitialTime: (duration: number) => void;
|
||||
}
|
||||
|
||||
// Create the context with a default value of `undefined`
|
||||
const TimerContext = createContext<TimerContextType | undefined>(undefined);
|
||||
|
||||
// Provider Component
|
||||
export const TimerProvider: React.FC<{ children: React.ReactNode }> = ({
|
||||
children,
|
||||
}) => {
|
||||
const [timeRemaining, setTimeRemaining] = useState<number>(0); // Default is 0
|
||||
let timer: NodeJS.Timeout;
|
||||
const [timeRemaining, setTimeRemaining] = useState<number>(0);
|
||||
const timerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// countdown effect
|
||||
useEffect(() => {
|
||||
if (timeRemaining > 0) {
|
||||
timer = setInterval(() => {
|
||||
if (timeRemaining > 0 && !timerRef.current) {
|
||||
timerRef.current = setInterval(() => {
|
||||
setTimeRemaining((prev) => {
|
||||
if (prev <= 1) {
|
||||
clearInterval(timer);
|
||||
clearInterval(timerRef.current!);
|
||||
timerRef.current = null;
|
||||
return 0;
|
||||
}
|
||||
return prev - 1;
|
||||
@ -34,20 +39,29 @@ export const TimerProvider: React.FC<{ children: React.ReactNode }> = ({
|
||||
}
|
||||
|
||||
return () => {
|
||||
clearInterval(timer); // Cleanup timer on unmount
|
||||
if (timerRef.current) {
|
||||
clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [timeRemaining]);
|
||||
|
||||
const resetTimer = (duration: number) => {
|
||||
clearInterval(timer);
|
||||
if (timerRef.current) clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
setTimeRemaining(duration);
|
||||
};
|
||||
|
||||
const stopTimer = () => {
|
||||
clearInterval(timer);
|
||||
if (timerRef.current) {
|
||||
clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const setInitialTime = (duration: number) => {
|
||||
if (timerRef.current) clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
setTimeRemaining(duration);
|
||||
};
|
||||
|
||||
@ -60,7 +74,6 @@ export const TimerProvider: React.FC<{ children: React.ReactNode }> = ({
|
||||
);
|
||||
};
|
||||
|
||||
// Hook to use the TimerContext
|
||||
export const useTimer = (): TimerContextType => {
|
||||
const context = useContext(TimerContext);
|
||||
if (!context) {
|
||||
|
||||
Reference in New Issue
Block a user