Skip to content

Commit 7097f7d

Browse files
authored
Merge pull request #263 from codeunia-dev/feat/profilepicture
feat(users): Enhance profile picture upload with avatar cleanup
2 parents e869f3d + ebc7199 commit 7097f7d

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

components/users/ProfilePictureUpload.tsx

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,32 @@ export function ProfilePictureUpload({
7777
}
7878
}
7979

80+
const deleteOldAvatar = async (oldAvatarUrl: string) => {
81+
try {
82+
const supabase = createClient()
83+
84+
// Extract file path from URL
85+
// URL format: https://.../storage/v1/object/public/profile-pictures/avatars/filename.jpg
86+
const urlParts = oldAvatarUrl.split('/storage/v1/object/public/profile-pictures/')
87+
if (urlParts.length < 2) return
88+
89+
const filePath = urlParts[1]
90+
91+
// Delete the old file
92+
const { error } = await supabase.storage
93+
.from('profile-pictures')
94+
.remove([filePath])
95+
96+
if (error) {
97+
console.error('Error deleting old avatar:', error)
98+
// Don't throw - we still want the upload to succeed even if deletion fails
99+
}
100+
} catch (err) {
101+
console.error('Error in deleteOldAvatar:', err)
102+
// Don't throw - non-critical error
103+
}
104+
}
105+
80106
const handleCropComplete = async (croppedImageBlob: Blob) => {
81107
try {
82108
setUploading(true)
@@ -85,6 +111,11 @@ export function ProfilePictureUpload({
85111

86112
const supabase = createClient()
87113

114+
// Delete old avatar if it exists
115+
if (previewUrl) {
116+
await deleteOldAvatar(previewUrl)
117+
}
118+
88119
// Create a unique file name
89120
const fileName = `${userId}-${Date.now()}.jpg`
90121
const filePath = `avatars/${fileName}`
@@ -143,6 +174,11 @@ export function ProfilePictureUpload({
143174

144175
const supabase = createClient()
145176

177+
// Delete the avatar file from storage
178+
if (previewUrl) {
179+
await deleteOldAvatar(previewUrl)
180+
}
181+
146182
// Update profile to remove avatar
147183
const { error: updateError } = await supabase
148184
.from('profiles')

0 commit comments

Comments
 (0)