fix(api): fix api logic for exam screen

needs more work for the timercontext
This commit is contained in:
shafin-r
2025-08-31 02:20:55 +06:00
parent 08a560abe5
commit b112a8fdac
7 changed files with 301 additions and 684 deletions

View File

@ -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) {