Files
examjam-frontend/components/AuthInitializer.tsx

50 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"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, token, hydrated } = useAuthStore();
const router = useRouter();
const pathname = usePathname();
// 1⃣ Run initialization once
useEffect(() => {
initializeAuth();
}, [initializeAuth]);
// 2⃣ Run routing logic only after hydration
useEffect(() => {
if (!hydrated) return;
const publicPages = ["/", "/login", "/register"];
if (token) {
if (publicPages.includes(pathname)) {
router.replace("/home");
}
} else {
if (!publicPages.includes(pathname)) {
router.replace("/login");
}
}
}, [pathname, token, hydrated, router]);
// 3⃣ Show loading until hydrated
if (!hydrated) {
return (
<div className="min-h-screen flex flex-col justify-center items-center gap-3">
<div className="animate-spin rounded-full h-20 w-20 border-b-2 border-blue-500"></div>
<p className="text-2xl font-semibold tracking-tighter">Loading...</p>
</div>
);
}
return <>{children}</>;
}