Fix avatar loading by preventing profile state race condition

This commit is contained in:
gpt-engineer-app[bot]
2025-10-13 17:13:37 +00:00
parent 7d6c0aabcf
commit 5863a49d3a
2 changed files with 17 additions and 20 deletions

View File

@@ -97,7 +97,7 @@ export function AuthButtons() {
return <DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="relative h-8 w-8 rounded-full">
<Avatar className="h-8 w-8">
<Avatar className="h-8 w-8" key={profile?.avatar_url || 'fallback'}>
<AvatarImage
src={profile?.avatar_url || undefined}
alt={profile?.display_name || profile?.username || user.email || 'User avatar'}

View File

@@ -44,26 +44,22 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
if (error && error.code !== 'PGRST116') {
authError('[Auth] Error fetching profile:', error);
if (isMountedRef.current) {
setProfile(null);
}
// Don't clear profile on error - keep existing data
return;
}
if (isMountedRef.current) {
if (isMountedRef.current && data) {
console.log('[Auth] ✅ Profile loaded:', {
userId: data?.user_id,
username: data?.username,
avatar_url: data?.avatar_url,
userId: data.user_id,
username: data.username,
avatar_url: data.avatar_url,
hasData: !!data
});
setProfile(data as Profile);
}
} catch (error) {
authError('[Auth] Error fetching profile:', error);
if (isMountedRef.current) {
setProfile(null);
}
// Don't clear profile on error - keep existing data
}
};
@@ -220,17 +216,18 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
// Handle profile fetching for authenticated users (async, doesn't block loading)
if (session?.user) {
// Only fetch if we don't have a profile or user ID changed
if (!profile || profile.user_id !== session.user.id) {
if (profileFetchTimeoutRef.current) {
clearTimeout(profileFetchTimeoutRef.current);
profileFetchTimeoutRef.current = null;
}
profileFetchTimeoutRef.current = setTimeout(() => {
// Call directly - fetchProfile is already async
fetchProfile(session.user.id);
profileFetchTimeoutRef.current = null;
}, 0);
} else {
setProfile(null);
}
}
// Profile is already cleared in SIGNED_OUT handler above
});
// THEN get initial session (this may trigger INITIAL_SESSION event)