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}</>;
|
||||
}
|
||||
Reference in New Issue
Block a user