From e99c4d96ee73d0fee32403b262a49868ae5458f2 Mon Sep 17 00:00:00 2001 From: StarAppeal Date: Sat, 7 Dec 2024 23:02:30 +0100 Subject: [PATCH] add loading mechanism to AuthProvider.tsx --- src/components/AuthenticatedWrapper.tsx | 6 +++++- src/context/AuthProvider.tsx | 7 ++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/components/AuthenticatedWrapper.tsx b/src/components/AuthenticatedWrapper.tsx index d877149..a460ae7 100644 --- a/src/components/AuthenticatedWrapper.tsx +++ b/src/components/AuthenticatedWrapper.tsx @@ -3,7 +3,11 @@ import {useAuth} from "@/src/context/AuthProvider"; import NotAuthenticated from "@/src/components/NotAuthenticated"; const AuthenticatedWrapper: React.FC<{ children: React.ReactNode }> = ({children}) => { - const {isAuthenticated} = useAuth(); + const {isAuthenticated, loading} = useAuth(); + + if (loading) { + return null; + } if (!isAuthenticated) { return ; diff --git a/src/context/AuthProvider.tsx b/src/context/AuthProvider.tsx index 69872ba..b670b86 100644 --- a/src/context/AuthProvider.tsx +++ b/src/context/AuthProvider.tsx @@ -15,6 +15,7 @@ type AuthContextType = { logout: () => Promise; error: AuthError | null; authenticatedUser: User | null; + loading: boolean; }; const AuthContext = createContext(undefined); @@ -24,6 +25,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({children} const [authenticatedUser, setAuthenticatedUser] = useState(null); const [token, setToken] = useState(null); const [error, setError] = useState(null); + const [loading, setLoading] = useState(true); useEffect(() => { const checkAuthStatus = async () => { @@ -35,6 +37,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({children} } else { setIsAuthenticated(false); } + setLoading(false); }; checkAuthStatus(); @@ -77,6 +80,8 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({children} // correctly logged in, reset error setError(null); await saveUser(response.token) + // needed? + setLoading(false); }; const logout = async () => { @@ -86,7 +91,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({children} }; return ( - + {children} );