diff --git a/src/hooks/useAuth.tsx b/src/hooks/useAuth.tsx index 87335f99..2d6896e8 100644 --- a/src/hooks/useAuth.tsx +++ b/src/hooks/useAuth.tsx @@ -181,11 +181,20 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) { setSession(session); setUser(session.user); sessionVerifiedRef.current = true; - } else if (event === 'INITIAL_SESSION' && session) { - console.log('[Auth] INITIAL_SESSION detected, setting session and user'); - setSession(session); - setUser(session.user); - sessionVerifiedRef.current = true; + } else if (event === 'INITIAL_SESSION') { + if (session) { + console.log('[Auth] INITIAL_SESSION detected with session, setting user'); + setSession(session); + setUser(session.user); + sessionVerifiedRef.current = true; + } else { + console.log('[Auth] INITIAL_SESSION detected with NO session - user not logged in'); + setSession(null); + setUser(null); + setProfile(null); + sessionVerifiedRef.current = false; + setLoading(false); + } } else if (event === 'SIGNED_OUT') { console.log('[Auth] SIGNED_OUT detected, clearing session'); setSession(null); @@ -272,7 +281,7 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) { } // Defer profile fetch to avoid deadlock - const shouldWaitForProfile = event === 'SIGNED_IN' || event === 'INITIAL_SESSION'; + const shouldWaitForProfile = (event === 'SIGNED_IN' || event === 'INITIAL_SESSION') && session !== null; console.log('[Auth] Profile fetch deferred, shouldWaitForProfile:', shouldWaitForProfile, 'event:', event); profileFetchTimeoutRef.current = setTimeout(() => { if (!isMountedRef.current) return; @@ -287,6 +296,11 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) { } else { if (isMountedRef.current) { setProfile(null); + // If no session and this is an init event, resolve loading immediately + if (event === 'INITIAL_SESSION' || event === 'SIGNED_OUT') { + console.log('[Auth] No session for event:', event, '- setting loading to false'); + setLoading(false); + } } }