diff --git a/src/contexts/AuthContext.tsx b/src/contexts/AuthContext.tsx index 2718e15..1add954 100644 --- a/src/contexts/AuthContext.tsx +++ b/src/contexts/AuthContext.tsx @@ -14,6 +14,7 @@ interface AuthContextType { user: User | null; login: (email: string, password: string) => Promise; logout: () => void; + isLoading: boolean; } type AuthProviderProps = { @@ -33,29 +34,38 @@ export const AuthProvider: React.FC = ({ children }) => { const [isAuthenticated, setIsAuthenticated] = useState(getInitialAuthState); const [user, setUser] = useState(null); + const [isLoading, setIsLoading] = useState(true); useEffect(() => { - localStorage.setItem("isAuthenticated", JSON.stringify(isAuthenticated)); + if (isAuthenticated) { + localStorage.setItem("isAuthenticated", JSON.stringify(isAuthenticated)); + } else { + localStorage.removeItem("isAuthenticated"); + } }, [isAuthenticated]); useEffect(() => { if (isAuthenticated) { const fetchUser = async () => { try { + setIsLoading(true); const data = await me(); + setIsAuthenticated(true); setUser(data); } catch (error) { console.error("Failed to fetch user data:", error); setIsAuthenticated(false); setUser(null); + } finally { + setIsLoading(false); } }; fetchUser(); } else { - setUser(null); + setIsLoading(false); } - }, [isAuthenticated]); + }, [isAuthenticated]); // Dependencies are correctly managed const login = useCallback(async (email: string, password: string) => { try { @@ -64,9 +74,13 @@ export const AuthProvider: React.FC = ({ children }) => { setIsAuthenticated(true); setUser(data); } catch (error) { + console.error( + "Login failed:", + error instanceof Error ? error.message : "Unknown error" + ); setIsAuthenticated(false); setUser(null); - throw new Error(error instanceof Error ? error.message : "Unknown error"); + throw error; } }, []); @@ -77,7 +91,9 @@ export const AuthProvider: React.FC = ({ children }) => { }, []); return ( - + {children} ); diff --git a/src/layouts/ProtectedPage.tsx b/src/layouts/ProtectedPage.tsx index d23fc96..e4da02d 100644 --- a/src/layouts/ProtectedPage.tsx +++ b/src/layouts/ProtectedPage.tsx @@ -1,10 +1,19 @@ import { useAuth } from "@/hooks/useAuth"; +import { Spin } from "antd"; import { Navigate, Outlet } from "react-router-dom"; const ProtectedPage = () => { - const { isAuthenticated } = useAuth(); + const { user, isLoading } = useAuth(); - if (!isAuthenticated) { + if (isLoading) { + return ( +
+ +
+ ); + } + + if (!user) { return ; }