File size: 2,406 Bytes
6711fd5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | import { useState, useCallback } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { supabase } from '@/integrations/supabase/client';
import { toast } from 'sonner';
export interface ProfileUpdateData {
display_name?: string;
bio?: string;
avatar_url?: string;
}
export const useProfileUpdate = () => {
const { user, refreshProfile } = useAuth();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const updateProfile = useCallback(async (updates: ProfileUpdateData) => {
if (!user) {
setError('يجب تسجيل الدخول أولاً');
return false;
}
setIsLoading(true);
setError(null);
try {
if (updates.display_name && updates.display_name.trim().length < 2) {
throw new Error('اسم العرض يجب أن يكون 2 أحرف على الأقل');
}
if (updates.bio && updates.bio.trim().length > 500) {
throw new Error('النبذة التعريفية يجب أن تكون أقل من 500 حرف');
}
const { error: supabaseError } = await supabase
.from('profiles')
.update({
display_name: updates.display_name?.trim(),
bio: updates.bio?.trim(),
avatar_url: updates.avatar_url,
updated_at: new Date().toISOString(),
})
.eq('user_id', user.id);
if (supabaseError) throw supabaseError;
await refreshProfile();
toast.success('تم تحديث الملف الشخصي بنجاح ✓');
return true;
} catch (err: any) {
const errorMessage = err.message || 'حدث خطأ أثناء تحديث الملف الشخصي';
setError(errorMessage);
toast.error(errorMessage);
return false;
} finally {
setIsLoading(false);
}
}, [user, refreshProfile]);
const updateAvatar = useCallback(async (avatarUrl: string) => {
return updateProfile({ avatar_url: avatarUrl });
}, [updateProfile]);
const updateBio = useCallback(async (bio: string) => {
return updateProfile({ bio });
}, [updateProfile]);
const updateDisplayName = useCallback(async (displayName: string) => {
return updateProfile({ display_name: displayName });
}, [updateProfile]);
return {
isLoading,
error,
updateProfile,
updateAvatar,
updateBio,
updateDisplayName,
};
};
|