generated from muhtadeetaron/nextjs-template
fix(ts): refactor codebase for capacitor setup
This commit is contained in:
@ -9,28 +9,39 @@ import FormField from "@/components/FormField";
|
||||
import { login } from "@/lib/auth";
|
||||
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { LoginForm } from "@/types/auth";
|
||||
|
||||
const page = () => {
|
||||
const LoginPage = () => {
|
||||
const router = useRouter();
|
||||
const { setToken } = useAuth();
|
||||
const [form, setForm] = useState({
|
||||
|
||||
const [form, setForm] = useState<LoginForm>({
|
||||
email: "",
|
||||
password: "",
|
||||
});
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
// For Rafeed
|
||||
// Function to login a user. I've kept it in a barebones form right now, but you can just call the login function from /lib/auth.ts and pass on the form.
|
||||
const loginUser = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
await login(form, setToken); // Call the login function
|
||||
router.push("/home"); // Redirect on successful login
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
setError(error.message); // Handle error messages
|
||||
await login(form, setToken);
|
||||
router.push("/home");
|
||||
} catch (err: unknown) {
|
||||
console.error(err);
|
||||
|
||||
if (
|
||||
typeof err === "object" &&
|
||||
err !== null &&
|
||||
"message" in err &&
|
||||
typeof err.message === "string"
|
||||
) {
|
||||
setError(err.message);
|
||||
} else {
|
||||
setError("An unexpected error occurred.");
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@ -63,13 +74,17 @@ const page = () => {
|
||||
title="Email Address"
|
||||
value={form.email}
|
||||
placeholder="Enter your email address..."
|
||||
handleChangeText={(e) => setForm({ ...form, email: e })}
|
||||
handleChangeText={(value) =>
|
||||
setForm({ ...form, email: value })
|
||||
}
|
||||
/>
|
||||
<FormField
|
||||
title="Password"
|
||||
value={form.password}
|
||||
placeholder="Enter a password"
|
||||
handleChangeText={(e) => setForm({ ...form, password: e })}
|
||||
handleChangeText={(value) =>
|
||||
setForm({ ...form, password: value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@ -94,7 +109,7 @@ const page = () => {
|
||||
className="text-center mb-[70px]"
|
||||
style={{ fontFamily: "Montserrat, sans-serif" }}
|
||||
>
|
||||
Don't have an account?{" "}
|
||||
Don't have an account?{" "}
|
||||
<Link href="/register" className="text-[#276ac0] hover:underline">
|
||||
Register here.
|
||||
</Link>
|
||||
@ -106,4 +121,4 @@ const page = () => {
|
||||
);
|
||||
};
|
||||
|
||||
export default page;
|
||||
export default LoginPage;
|
||||
|
||||
@ -10,11 +10,18 @@ import { useAuth } from "@/context/AuthContext";
|
||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||
import FormField from "@/components/FormField";
|
||||
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||
import { RegisterForm } from "@/types/auth";
|
||||
|
||||
interface CustomError extends Error {
|
||||
response?: {
|
||||
detail?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export default function RegisterPage() {
|
||||
const { setToken } = useAuth();
|
||||
const router = useRouter();
|
||||
const [form, setForm] = useState({
|
||||
const [form, setForm] = useState<RegisterForm>({
|
||||
name: "",
|
||||
institution: "",
|
||||
sscRoll: "",
|
||||
@ -25,13 +32,12 @@ export default function RegisterPage() {
|
||||
});
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleError = (error: any) => {
|
||||
const handleError = (error: { detail: string }) => {
|
||||
if (error?.detail) {
|
||||
const match = error.detail.match(/Key \((.*?)\)=\((.*?)\)/);
|
||||
if (match) {
|
||||
const field = match[1];
|
||||
const value = match[2];
|
||||
return `The ${field} already exists. Please use a different value.`;
|
||||
return `The ${field} already exists. Please try again.`;
|
||||
}
|
||||
}
|
||||
return "An unexpected error occurred. Please try again.";
|
||||
@ -56,16 +62,30 @@ export default function RegisterPage() {
|
||||
setError(validationError);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await register(form, setToken);
|
||||
router.push("/home");
|
||||
} catch (error: any) {
|
||||
console.error("Error:", error.response || error.message);
|
||||
if (error.response?.detail) {
|
||||
const decodedError = handleError({ detail: error.response.detail });
|
||||
setError(decodedError);
|
||||
} catch (error) {
|
||||
// Type guard for built-in Error type
|
||||
if (error instanceof Error) {
|
||||
console.error(
|
||||
"Error:",
|
||||
(error as CustomError).response || error.message
|
||||
);
|
||||
|
||||
const response = (error as CustomError).response;
|
||||
|
||||
if (response?.detail) {
|
||||
const decodedError = handleError({ detail: response.detail });
|
||||
setError(decodedError);
|
||||
} else {
|
||||
setError(error.message || "An unexpected error occurred.");
|
||||
}
|
||||
} else {
|
||||
setError(error.message || "An unexpected error occurred.");
|
||||
// Fallback for non-standard errors
|
||||
console.error("Unexpected error:", error);
|
||||
setError("An unexpected error occurred.");
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -148,7 +168,7 @@ export default function RegisterPage() {
|
||||
</button>
|
||||
|
||||
<p className="text-center text-sm">
|
||||
Already have an account?{" "}
|
||||
Already have an account?
|
||||
<Link href="/login" className="text-blue-600">
|
||||
Login here
|
||||
</Link>
|
||||
|
||||
@ -50,7 +50,7 @@ const QuestionItem = ({ question }: QuestionItemProps) => {
|
||||
|
||||
const BookmarkPage = () => {
|
||||
const router = useRouter();
|
||||
const [questions, setQuestions] = useState();
|
||||
const [questions, setQuestions] = useState<Question[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
fetch("/data/bookmark.json")
|
||||
@ -74,7 +74,7 @@ const BookmarkPage = () => {
|
||||
<ListFilter size={24} color="#113768" />
|
||||
</button>
|
||||
</div>
|
||||
{questions?.map((question) => (
|
||||
{questions.map((question: Question) => (
|
||||
<QuestionItem key={question.id} question={question} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
@ -1,7 +0,0 @@
|
||||
import React from "react";
|
||||
|
||||
const page = () => {
|
||||
return <div>page</div>;
|
||||
};
|
||||
|
||||
export default page;
|
||||
@ -1,57 +1,56 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect, ReactNode } from "react";
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Image from "next/image";
|
||||
import Header from "@/components/Header";
|
||||
import SlidingGallery from "@/components/SlidingGallery";
|
||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||
import { ChevronRight } from "lucide-react";
|
||||
import styles from "@/css/Home.module.css";
|
||||
import { API_URL } from "@/lib/auth";
|
||||
import { Avatar } from "@/components/ui/avatar";
|
||||
import { getLinkedViews } from "@/lib/gallery-views";
|
||||
import { getTopThree } from "@/lib/leaderboard";
|
||||
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||
import { GalleryViews } from "@/types/gallery";
|
||||
|
||||
interface LinkedView {
|
||||
interface LeaderboardEntry {
|
||||
id: string;
|
||||
content: ReactNode;
|
||||
name: string;
|
||||
points: number;
|
||||
}
|
||||
|
||||
const page = () => {
|
||||
const HomePage = () => {
|
||||
const router = useRouter();
|
||||
const [boardData, setBoardData] = useState([]);
|
||||
const [boardError, setBoardError] = useState(null);
|
||||
const [linkedViews, setLinkedViews] = useState<LinkedView[]>();
|
||||
|
||||
const performanceData = [
|
||||
{ label: "Mock Test", progress: 20 },
|
||||
{ label: "Topic Test", progress: 70 },
|
||||
{ label: "Subject Test", progress: 50 },
|
||||
];
|
||||
|
||||
const progressData = [
|
||||
{ label: "Physics", progress: 25 },
|
||||
{ label: "Chemistry", progress: 57 },
|
||||
];
|
||||
const [boardData, setBoardData] = useState<LeaderboardEntry[]>([]);
|
||||
const [boardError, setBoardError] = useState<string | null>(null);
|
||||
const [linkedViews, setLinkedViews] = useState<GalleryViews[]>();
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
async function fetchBoardData() {
|
||||
|
||||
const fetchBoardData = async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/leaderboard`);
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch leaderboard data");
|
||||
}
|
||||
const data = await response.json();
|
||||
|
||||
const data: LeaderboardEntry[] = await response.json();
|
||||
if (isMounted) setBoardData(data);
|
||||
} catch (error) {
|
||||
if (isMounted) setBoardError(error.message || "An error occurred");
|
||||
} catch (err) {
|
||||
if (isMounted) {
|
||||
const message =
|
||||
err instanceof Error ? err.message : "An unexpected error occurred";
|
||||
setBoardError(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
const fetchedLinkedViews = getLinkedViews();
|
||||
};
|
||||
|
||||
const fetchedLinkedViews: GalleryViews[] = getLinkedViews();
|
||||
setLinkedViews(fetchedLinkedViews);
|
||||
|
||||
fetchBoardData();
|
||||
|
||||
return () => {
|
||||
@ -157,20 +156,24 @@ const page = () => {
|
||||
</div>
|
||||
<div className={styles.divider}></div>
|
||||
<div className={styles.topThreeList}>
|
||||
{getTopThree(boardData).map((student, idx) => (
|
||||
<div key={idx} className={styles.topThreeItem}>
|
||||
<div className={styles.studentInfo}>
|
||||
<span className={styles.rank}>{student.rank}</span>
|
||||
<Avatar className="bg-slate-300 w-4 h-4 rounded-full"></Avatar>
|
||||
<span className={styles.studentName}>
|
||||
{student.name}
|
||||
{boardError ? (
|
||||
<DestructibleAlert text={boardError} />
|
||||
) : (
|
||||
getTopThree(boardData).map((student, idx) => (
|
||||
<div key={idx} className={styles.topThreeItem}>
|
||||
<div className={styles.studentInfo}>
|
||||
<span className={styles.rank}>{student.rank}</span>
|
||||
<Avatar className="bg-slate-300 w-4 h-4 rounded-full" />
|
||||
<span className={styles.studentName}>
|
||||
{student.name}
|
||||
</span>
|
||||
</div>
|
||||
<span className={styles.points}>
|
||||
{student.points}pt
|
||||
</span>
|
||||
</div>
|
||||
<span className={styles.points}>
|
||||
{student.points}pt
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -232,4 +235,4 @@ const page = () => {
|
||||
);
|
||||
};
|
||||
|
||||
export default page;
|
||||
export default HomePage;
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||
import Header from "@/components/Header";
|
||||
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { API_URL, getToken } from "@/lib/auth";
|
||||
import { BoardData, getLeaderboard } from "@/lib/leaderboard";
|
||||
@ -40,7 +41,14 @@ const LeaderboardPage = () => {
|
||||
setUserData(fetchedUserData);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
setUserData(undefined);
|
||||
setUserData({
|
||||
name: "",
|
||||
institution: "",
|
||||
sscRoll: "",
|
||||
hscRoll: "",
|
||||
email: "",
|
||||
phone: "",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -97,6 +105,33 @@ const LeaderboardPage = () => {
|
||||
return result ? [{ ...result, rank: sortedData.indexOf(result) + 1 }] : [];
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<BackgroundWrapper>
|
||||
<section>
|
||||
<Header displayTabTitle="Leaderboard" />
|
||||
<section className="flex flex-col mx-10 pt-10 space-y-4">
|
||||
<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">Loading...</p>
|
||||
</section>
|
||||
</section>
|
||||
</BackgroundWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
if (boardError) {
|
||||
return (
|
||||
<BackgroundWrapper>
|
||||
<section>
|
||||
<Header displayTabTitle="Leaderboard" />
|
||||
<section className="flex flex-col mx-10 pt-10 space-y-4">
|
||||
<DestructibleAlert text={boardError} />
|
||||
</section>
|
||||
</section>
|
||||
</BackgroundWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<BackgroundWrapper>
|
||||
<section>
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
import Header from "@/components/Header";
|
||||
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||
@ -15,7 +15,7 @@ interface Mock {
|
||||
rating: number;
|
||||
}
|
||||
|
||||
export default function PaperScreen() {
|
||||
function PaperPageContent() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const name = searchParams.get("name") || "";
|
||||
@ -23,7 +23,6 @@ export default function PaperScreen() {
|
||||
const [questions, setQuestions] = useState<Mock[] | null>(null);
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||
const [refreshing, setRefreshing] = useState<boolean>(false);
|
||||
const [componentKey, setComponentKey] = useState<number>(0);
|
||||
|
||||
async function fetchMocks() {
|
||||
try {
|
||||
@ -45,12 +44,7 @@ export default function PaperScreen() {
|
||||
|
||||
const onRefresh = async () => {
|
||||
setRefreshing(true);
|
||||
|
||||
await fetchMocks();
|
||||
setComponentKey((prevKey) => prevKey + 1);
|
||||
setTimeout(() => {
|
||||
setRefreshing(false);
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
if (errorMsg) {
|
||||
@ -124,3 +118,20 @@ export default function PaperScreen() {
|
||||
</BackgroundWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
export default function PaperScreen() {
|
||||
<Suspense
|
||||
fallback={
|
||||
<BackgroundWrapper>
|
||||
<div className="min-h-screen">
|
||||
<div className="mx-10 mt-10 flex flex-col justify-center items-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">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
</BackgroundWrapper>
|
||||
}
|
||||
>
|
||||
<PaperPageContent />
|
||||
</Suspense>;
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { API_URL, getToken } from "@/lib/auth";
|
||||
import { UserData } from "@/types/auth";
|
||||
import {
|
||||
Bookmark,
|
||||
ChartColumn,
|
||||
@ -22,7 +23,14 @@ import React, { useEffect, useState } from "react";
|
||||
|
||||
const SettingsPage = () => {
|
||||
const router = useRouter();
|
||||
const [userData, setUserData] = useState(null);
|
||||
const [userData, setUserData] = useState<UserData>({
|
||||
name: "",
|
||||
institution: "",
|
||||
sscRoll: "",
|
||||
hscRoll: "",
|
||||
email: "",
|
||||
phone: "",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchUser() {
|
||||
|
||||
@ -16,21 +16,18 @@ const units = [
|
||||
const Unit = () => {
|
||||
const router = useRouter();
|
||||
|
||||
const handleUnitPress = (unit) => {
|
||||
const handleUnitPress = (unit: {
|
||||
id?: number;
|
||||
name: string;
|
||||
rating?: number;
|
||||
}) => {
|
||||
router.push(`/paper?name=${encodeURIComponent(unit.name)}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<BackgroundWrapper>
|
||||
<div className="flex flex-col min-h-screen">
|
||||
<Header
|
||||
displayExamInfo={null}
|
||||
displayTabTitle={"Units"}
|
||||
displaySubject={null}
|
||||
displayUser={false}
|
||||
title=""
|
||||
image={""}
|
||||
/>
|
||||
<Header displayTabTitle="Units" />
|
||||
<div className="flex-1">
|
||||
<div className="overflow-y-auto">
|
||||
<div className="border border-blue-200 gap-4 rounded-3xl p-4 mx-10 mt-10">
|
||||
|
||||
@ -6,71 +6,11 @@ import { useTimer } from "@/context/TimerContext";
|
||||
import { useExam } from "@/context/ExamContext";
|
||||
import { API_URL, getToken } from "@/lib/auth";
|
||||
import Header from "@/components/Header";
|
||||
import { Bookmark, BookmarkCheck } from "lucide-react";
|
||||
import { useModal } from "@/context/ModalContext";
|
||||
import Modal from "@/components/ExamModal";
|
||||
import { Question } from "@/types/exam";
|
||||
import QuestionItem from "@/components/QuestionItem";
|
||||
|
||||
// Types
|
||||
// interface Question {
|
||||
// id: number;
|
||||
// question: string;
|
||||
// options: Record<string, string>;
|
||||
// }
|
||||
|
||||
// interface QuestionItemProps {
|
||||
// question: Question;
|
||||
// selectedAnswer?: string;
|
||||
// handleSelect: (questionId: number, option: string) => void;
|
||||
// }
|
||||
|
||||
// const QuestionItem = React.memo<QuestionItemProps>(
|
||||
// ({ question, selectedAnswer, handleSelect }) => {
|
||||
// const [bookmark, setBookmark] = useState(false);
|
||||
|
||||
// return (
|
||||
// <div className="border-[0.5px] border-[#8abdff]/60 rounded-2xl p-4 flex flex-col">
|
||||
// <h3 className="text-xl font-medium mb-[20px]">
|
||||
// {question.id}. {question.question}
|
||||
// </h3>
|
||||
// <div className="flex justify-between items-center">
|
||||
// <div></div>
|
||||
// <button onClick={() => setBookmark(!bookmark)}>
|
||||
// {bookmark ? (
|
||||
// <BookmarkCheck size={25} color="#113768" />
|
||||
// ) : (
|
||||
// <Bookmark size={25} color="#113768" />
|
||||
// )}
|
||||
// </button>
|
||||
// </div>
|
||||
// <div className="flex flex-col gap-4 items-start">
|
||||
// {Object.entries(question.options).map(([key, value]) => (
|
||||
// <button
|
||||
// key={key}
|
||||
// className="flex items-center gap-3"
|
||||
// onClick={() => handleSelect(question.id, key)}
|
||||
// >
|
||||
// <span
|
||||
// className={`flex items-center rounded-full border px-1.5 ${
|
||||
// selectedAnswer === key
|
||||
// ? "text-white bg-[#113768] border-[#113768]"
|
||||
// : ""
|
||||
// }`}
|
||||
// >
|
||||
// {key.toUpperCase()}
|
||||
// </span>
|
||||
// <span className="option-description">{value}</span>
|
||||
// </button>
|
||||
// ))}
|
||||
// </div>
|
||||
// </div>
|
||||
// );
|
||||
// }
|
||||
// );
|
||||
|
||||
// QuestionItem.displayName = "QuestionItem";
|
||||
|
||||
export default function ExamPage() {
|
||||
// All hooks at the top - no conditional calls
|
||||
const router = useRouter();
|
||||
@ -280,13 +220,7 @@ export default function ExamPage() {
|
||||
// Render the main exam interface
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Header
|
||||
examDuration={time}
|
||||
displayTabTitle={null}
|
||||
image={undefined}
|
||||
displayUser={undefined}
|
||||
displaySubject={undefined}
|
||||
/>
|
||||
<Header examDuration={time} />
|
||||
<Modal open={isOpen} onClose={close} title={currentExam?.title}>
|
||||
{currentAttempt ? (
|
||||
<div>
|
||||
@ -301,8 +235,8 @@ export default function ExamPage() {
|
||||
<p className="">
|
||||
Skipped:{" "}
|
||||
<span className="text-yellow-600 font-bold">
|
||||
{currentExam?.questions.length -
|
||||
currentAttempt?.answers.length}
|
||||
{(currentExam?.questions?.length ?? 0) -
|
||||
(currentAttempt?.answers?.length ?? 0)}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
import { ArrowLeft, HelpCircle, Clock, XCircle } from "lucide-react";
|
||||
import DestructibleAlert from "@/components/DestructibleAlert";
|
||||
import BackgroundWrapper from "@/components/BackgroundWrapper";
|
||||
@ -18,47 +18,46 @@ interface Metadata {
|
||||
};
|
||||
}
|
||||
|
||||
export default function PretestPage() {
|
||||
function PretestPageContent() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const [examData, setExamData] = useState<Exam>();
|
||||
const { startExam, setCurrentExam } = useExam();
|
||||
|
||||
// Get params from URL search params
|
||||
const name = searchParams.get("name") || "";
|
||||
const id = searchParams.get("id") || "";
|
||||
const title = searchParams.get("title") || "";
|
||||
const rating = searchParams.get("rating") || "";
|
||||
|
||||
const [metadata, setMetadata] = useState<Metadata | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function fetchQuestions() {
|
||||
if (!id) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const questionResponse = await fetch(`${API_URL}/mock/${id}`, {
|
||||
method: "GET",
|
||||
});
|
||||
if (!questionResponse.ok) {
|
||||
throw new Error("Failed to fetch questions");
|
||||
}
|
||||
const data = await questionResponse.json();
|
||||
const fetchedMetadata: Metadata = data;
|
||||
|
||||
setExamData(data);
|
||||
setMetadata(fetchedMetadata);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
setError(error instanceof Error ? error.message : "An error occurred");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
const [error, setError] = useState<string>();
|
||||
console.log(loading);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchQuestions() {
|
||||
if (!id) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const questionResponse = await fetch(`${API_URL}/mock/${id}`, {
|
||||
method: "GET",
|
||||
});
|
||||
if (!questionResponse.ok) {
|
||||
throw new Error("Failed to fetch questions");
|
||||
}
|
||||
const data = await questionResponse.json();
|
||||
const fetchedMetadata: Metadata = data;
|
||||
|
||||
setExamData(data);
|
||||
setMetadata(fetchedMetadata);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
setError(error instanceof Error ? error.message : "An error occurred");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
if (id) {
|
||||
fetchQuestions();
|
||||
}
|
||||
@ -74,15 +73,16 @@ export default function PretestPage() {
|
||||
</button>
|
||||
<DestructibleAlert text={error} extraStyles="" />
|
||||
</div>
|
||||
{/* <CustomBackHandler fallbackRoute="paper" /> */}
|
||||
</div>
|
||||
</BackgroundWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
function handleStartExam() {
|
||||
if (!examData) return;
|
||||
|
||||
setCurrentExam(examData);
|
||||
startExam(examData); // Pass examData directly
|
||||
startExam(examData);
|
||||
router.push(`/exam/${id}?time=${metadata?.metadata.duration}`);
|
||||
}
|
||||
return (
|
||||
@ -192,3 +192,22 @@ export default function PretestPage() {
|
||||
</BackgroundWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
export default function PretestPage() {
|
||||
return (
|
||||
<Suspense
|
||||
fallback={
|
||||
<BackgroundWrapper>
|
||||
<div className="min-h-screen">
|
||||
<div className="mx-10 mt-10 flex flex-col justify-center items-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">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
</BackgroundWrapper>
|
||||
}
|
||||
>
|
||||
<PretestPageContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,13 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useExam, useExamResults } from "@/context/ExamContext";
|
||||
import { useExam } from "@/context/ExamContext";
|
||||
import { useEffect, useState } from "react";
|
||||
import React from "react";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
import SlidingGallery from "@/components/SlidingGallery";
|
||||
import QuestionItem from "@/components/QuestionItem";
|
||||
import { getResultViews } from "@/lib/gallery-views";
|
||||
import { Question } from "@/types/exam";
|
||||
|
||||
export default function ResultsPage() {
|
||||
const router = useRouter();
|
||||
@ -58,15 +59,15 @@ export default function ResultsPage() {
|
||||
|
||||
const apiResponse = getApiResponse();
|
||||
|
||||
const timeTaken =
|
||||
currentAttempt.endTime && currentAttempt.startTime
|
||||
? Math.round(
|
||||
(currentAttempt.endTime.getTime() -
|
||||
currentAttempt.startTime.getTime()) /
|
||||
1000 /
|
||||
60
|
||||
)
|
||||
: 0;
|
||||
// const timeTaken =
|
||||
// currentAttempt.endTime && currentAttempt.startTime
|
||||
// ? Math.round(
|
||||
// (currentAttempt.endTime.getTime() -
|
||||
// currentAttempt.startTime.getTime()) /
|
||||
// 1000 /
|
||||
// 60
|
||||
// )
|
||||
// : 0;
|
||||
|
||||
const views = getResultViews(currentAttempt);
|
||||
|
||||
@ -98,11 +99,13 @@ export default function ResultsPage() {
|
||||
Solutions
|
||||
</h3>
|
||||
<div className="flex flex-col gap-7">
|
||||
{apiResponse.questions.map((question) => (
|
||||
{apiResponse.questions.map((question: Question) => (
|
||||
<QuestionItem
|
||||
key={question.id}
|
||||
question={question}
|
||||
selectedAnswer={currentAttempt.answers[question.id - 1]}
|
||||
selectedAnswer={
|
||||
currentAttempt.answers[parseInt(question.id) - 1]
|
||||
}
|
||||
mode="result"
|
||||
/>
|
||||
))}
|
||||
|
||||
@ -53,7 +53,7 @@ export default function Home() {
|
||||
className="text-center font-medium"
|
||||
style={{ fontFamily: "Montserrat, sans-serif" }}
|
||||
>
|
||||
Don't have an account?{" "}
|
||||
Don't have an account?
|
||||
<Link href="/register" className="text-[#276ac0] hover:underline">
|
||||
Register here
|
||||
</Link>
|
||||
|
||||
Reference in New Issue
Block a user