From ebc7199fba363fe42202c54e9ffb499479b39f26 Mon Sep 17 00:00:00 2001 From: Akshay Date: Mon, 3 Nov 2025 11:10:58 +0530 Subject: [PATCH] feat(users): Enhance profile picture upload with avatar cleanup - Add deleteOldAvatar function to remove previous profile pictures from storage - Implement automatic deletion of old avatar when uploading a new profile picture - Add avatar deletion when removing profile picture - Improve error handling for avatar storage operations - Prevent storage accumulation of unused avatar files --- components/users/ProfilePictureUpload.tsx | 36 +++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/components/users/ProfilePictureUpload.tsx b/components/users/ProfilePictureUpload.tsx index 33285573..6f37441e 100644 --- a/components/users/ProfilePictureUpload.tsx +++ b/components/users/ProfilePictureUpload.tsx @@ -77,6 +77,32 @@ export function ProfilePictureUpload({ } } + const deleteOldAvatar = async (oldAvatarUrl: string) => { + try { + const supabase = createClient() + + // Extract file path from URL + // URL format: https://.../storage/v1/object/public/profile-pictures/avatars/filename.jpg + const urlParts = oldAvatarUrl.split('/storage/v1/object/public/profile-pictures/') + if (urlParts.length < 2) return + + const filePath = urlParts[1] + + // Delete the old file + const { error } = await supabase.storage + .from('profile-pictures') + .remove([filePath]) + + if (error) { + console.error('Error deleting old avatar:', error) + // Don't throw - we still want the upload to succeed even if deletion fails + } + } catch (err) { + console.error('Error in deleteOldAvatar:', err) + // Don't throw - non-critical error + } + } + const handleCropComplete = async (croppedImageBlob: Blob) => { try { setUploading(true) @@ -85,6 +111,11 @@ export function ProfilePictureUpload({ const supabase = createClient() + // Delete old avatar if it exists + if (previewUrl) { + await deleteOldAvatar(previewUrl) + } + // Create a unique file name const fileName = `${userId}-${Date.now()}.jpg` const filePath = `avatars/${fileName}` @@ -143,6 +174,11 @@ export function ProfilePictureUpload({ const supabase = createClient() + // Delete the avatar file from storage + if (previewUrl) { + await deleteOldAvatar(previewUrl) + } + // Update profile to remove avatar const { error: updateError } = await supabase .from('profiles')