fix(nav): improve navigation for authorization routes

This commit is contained in:
shafin-r
2025-09-08 14:15:27 +06:00
parent 99d6c15e38
commit 53a2228dc9
9 changed files with 55 additions and 63 deletions

View File

@ -9,32 +9,41 @@ export default function AuthInitializer({
}: {
children: React.ReactNode;
}) {
const { initializeAuth, isLoading, token } = useAuthStore();
const { initializeAuth, token, hydrated } = useAuthStore();
const router = useRouter();
const pathname = usePathname();
// 1⃣ Run initialization once
useEffect(() => {
const run = async () => {
await initializeAuth();
initializeAuth();
}, [initializeAuth]);
// Routing logic based on auth state
const publicPages = ["/", "/login", "/register"];
// 2⃣ Run routing logic only after hydration
useEffect(() => {
if (!hydrated) return;
if (token) {
if (publicPages.includes(pathname)) {
router.replace("/home");
}
} else {
if (!publicPages.includes(pathname)) {
router.replace("/");
}
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]);
run();
}, [pathname, token, initializeAuth, router]);
if (isLoading) return <p>Loading...</p>;
// 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}</>;
}