generated from muhtadeetaron/nextjs-template
feat(zustand): add zustand stores for exam, timer and auth
This commit is contained in:
40
components/AuthInitializer.tsx
Normal file
40
components/AuthInitializer.tsx
Normal file
@ -0,0 +1,40 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { useAuthStore } from "@/stores/authStore";
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
|
||||
export default function AuthInitializer({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { initializeAuth, isLoading, token } = useAuthStore();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
|
||||
useEffect(() => {
|
||||
const run = async () => {
|
||||
await initializeAuth();
|
||||
|
||||
// Routing logic based on auth state
|
||||
const publicPages = ["/", "/login", "/register"];
|
||||
|
||||
if (token) {
|
||||
if (publicPages.includes(pathname)) {
|
||||
router.replace("/home");
|
||||
}
|
||||
} else {
|
||||
if (!publicPages.includes(pathname)) {
|
||||
router.replace("/");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
run();
|
||||
}, [pathname, token, initializeAuth, router]);
|
||||
|
||||
if (isLoading) return <p>Loading...</p>;
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
@ -2,7 +2,7 @@ import React, { JSX } from "react";
|
||||
|
||||
interface DestructibleAlertProps {
|
||||
text: string;
|
||||
icon: JSX.Element;
|
||||
icon?: JSX.Element;
|
||||
}
|
||||
|
||||
const DestructibleAlert: React.FC<DestructibleAlertProps> = ({
|
||||
|
||||
@ -9,6 +9,9 @@ import { useExam } from "@/context/ExamContext";
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { useModal } from "@/context/ModalContext";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { useAuthStore } from "@/stores/authStore";
|
||||
import { useTimerStore } from "@/stores/timerStore";
|
||||
import { useExamStore } from "@/stores/examStore";
|
||||
|
||||
interface HeaderProps {
|
||||
displayUser?: boolean;
|
||||
@ -23,9 +26,9 @@ const Header = ({
|
||||
}: HeaderProps) => {
|
||||
const router = useRouter();
|
||||
const { open } = useModal();
|
||||
const { cancelExam } = useExam();
|
||||
const { stopTimer, timeRemaining } = useTimer();
|
||||
const { user } = useAuth();
|
||||
const { cancelExam } = useExamStore();
|
||||
const { stopTimer, timeRemaining } = useTimerStore();
|
||||
const { user } = useAuthStore();
|
||||
|
||||
const showExitDialog = () => {
|
||||
const confirmed = window.confirm("Are you sure you want to quit the exam?");
|
||||
|
||||
Reference in New Issue
Block a user