NeahNew/components/auth/auth-check.tsx
2025-05-04 22:37:26 +02:00

37 lines
1.0 KiB
TypeScript

"use client";
import { useSession } from "next-auth/react";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useCallback } from "react";
export function AuthCheck({ children }: { children: React.ReactNode }) {
const { data: session, status } = useSession();
const pathname = usePathname();
const router = useRouter();
// Memoize the redirect logic to prevent unnecessary re-renders
const handleAuthRedirect = useCallback(() => {
if (status === "unauthenticated" && pathname !== "/signin") {
router.push("/signin");
}
}, [status, router, pathname]);
useEffect(() => {
// Use setTimeout to avoid immediate state updates during rendering
const timer = setTimeout(() => {
handleAuthRedirect();
}, 0);
return () => clearTimeout(timer);
}, [handleAuthRedirect]);
if (status === "loading") {
return <div>Chargement...</div>;
}
if (status === "unauthenticated" && pathname !== "/signin") {
return null;
}
return <>{children}</>;
}