update auth. deal with migraine

This commit is contained in:
2025-06-03 17:00:53 -05:00
parent a9e7d8e126
commit ef24642128
5 changed files with 252 additions and 241 deletions

View File

@ -3,8 +3,10 @@
import React, {
type ReactNode,
createContext,
useCallback,
useContext,
useEffect,
useRef,
useState,
} from 'react';
import {
@ -41,31 +43,26 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
const [profile, setProfile] = useState<Profile | null>(null);
const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isInitialized, setIsInitialized] = useState(false);
const fetchUserData = async () => {
const fetchingRef = useRef(false);
const fetchUserData = useCallback(async () => {
if (fetchingRef.current) return;
fetchingRef.current = true;
try {
setIsLoading(true);
// Get user data
const userResponse = await getUser();
if (!userResponse.success) {
const profileResponse = await getProfile();
if (!userResponse.success || !profileResponse.success) {
setUser(null);
setProfile(null);
setAvatarUrl(null);
return;
}
setUser(userResponse.data);
// Get profile data
const profileResponse = await getProfile();
if (!profileResponse.success) {
setProfile(null);
setAvatarUrl(null);
return;
}
setProfile(profileResponse.data);
// Get avatar URL if available
@ -74,16 +71,28 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
bucket: 'avatars',
url: profileResponse.data.avatar_url,
});
if (avatarResponse.success) {
setAvatarUrl(avatarResponse.data);
}
} else setAvatarUrl(null);
}
} catch (error) {
toast.error('Failed to load user data');
console.error(
'Auth fetch error: ',
error instanceof Error ?
`${error.message}` :
'Failed to load user data!'
);
if (!isInitialized) {
toast.error('Failed to load user data!');
}
} finally {
setIsLoading(false);
setIsInitialized(true);
fetchingRef.current = false;
}
};
}, [isInitialized]);
useEffect(() => {
const supabase = createClient();
@ -95,7 +104,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
const {
data: { subscription },
} = supabase.auth.onAuthStateChange(async (event, session) => {
if (event === 'SIGNED_IN' || event === 'TOKEN_REFRESHED') {
if (event === 'SIGNED_IN') {
await fetchUserData();
} else if (event === 'SIGNED_OUT') {
setUser(null);
@ -108,7 +117,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
return () => {
subscription.unsubscribe();
};
}, []);
}, [fetchUserData]);
const updateProfile = async (data: {
full_name?: string;
@ -116,9 +125,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
avatar_url?: string;
}) => {
try {
setIsLoading(true);
const result = await updateProfileAction(data);
if (!result.success) {
throw new Error(result.error ?? 'Failed to update profile');
}