fix: user can update avatar after first upload

This commit is contained in:
Sosokker 2024-11-07 04:21:17 +07:00
parent 1802f87bd5
commit 747fd57f14
3 changed files with 74 additions and 45 deletions

View File

@ -10,6 +10,12 @@ const nextConfig = {
port: "", port: "",
pathname: "/storage/v1/object/sign/**", pathname: "/storage/v1/object/sign/**",
}, },
{
protocol: "https",
hostname: SUPABASE_URL,
port: "",
pathname: "/storage/v1/object/public/**",
},
{ {
protocol: "https", protocol: "https",
hostname: "upload.wikimedia.org", hostname: "upload.wikimedia.org",
@ -19,7 +25,7 @@ const nextConfig = {
protocol: "https", protocol: "https",
hostname: "avatars.githubusercontent.com", hostname: "avatars.githubusercontent.com",
pathname: "/**", pathname: "/**",
} },
], ],
}, },
}; };

View File

@ -39,29 +39,56 @@ export default function EditProfilePage({ params }: { params: { uid: string } })
const onProfileSubmit = async (updates: z.infer<typeof profileSchema>) => { const onProfileSubmit = async (updates: z.infer<typeof profileSchema>) => {
const { avatars, username, full_name } = updates; const { avatars, username, full_name } = updates;
let avatarUrl = null;
try { try {
let avatarUrl = null;
if (avatars instanceof File) { if (avatars instanceof File) {
const { data: currentProfile, error: fetchError } = await client
.from("profiles")
.select("avatar_url")
.eq("id", uid)
.single();
if (fetchError) {
throw new Error("Failed to fetch existing profile data");
}
if (currentProfile?.avatar_url) {
const oldAvatarPath = currentProfile.avatar_url.split("/").pop();
const { error: deleteError } = await client.storage.from("avatars").remove([oldAvatarPath]);
if (deleteError) {
console.warn("Failed to delete old avatar:", deleteError.message);
}
}
const avatarData = await uploadAvatar(client, avatars, uid); const avatarData = await uploadAvatar(client, avatars, uid);
avatarUrl = avatarData?.path avatarUrl = avatarData?.path
? `${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/avatars/${avatarData.path}` ? `${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/avatars/${avatarData.path}`
: null; : null;
} }
const result = await updateProfile(client, uid, { const updateData = {
username, username,
full_name, full_name,
bio: bioContent, bio: bioContent,
...(avatarUrl && { avatar_url: avatarUrl }), ...(avatarUrl && { avatar_url: avatarUrl }),
}); };
const hasChanges = Object.values(updateData).some((value) => value !== undefined && value !== null);
if (!hasChanges) {
toast.error("No fields to update!");
return;
}
const result = await updateProfile(client, uid, updateData);
if (result) { if (result) {
toast.success("Profile updated successfully!"); toast.success("Profile updated successfully!");
router.push(`/profile/${uid}`); router.push(`/profile/${uid}`);
} else { } else {
toast.error("No fields to update!"); toast.error("Failed to update profile!");
} }
} catch (error) { } catch (error) {
toast.error("Error updating profile!"); toast.error("Error updating profile!");

View File

@ -1,48 +1,44 @@
import { SupabaseClient } from "@supabase/supabase-js"; import { SupabaseClient } from "@supabase/supabase-js";
interface UpdateData { interface UpdateData {
username?: string; username?: string;
full_name?: string; full_name?: string;
bio?: string; bio?: string;
updated_at?: Date; updated_at?: Date;
avatar_url?: string | null;
} }
export async function updateProfile( export async function updateProfile(supabase: SupabaseClient, userId: string, updates: UpdateData) {
supabase: SupabaseClient, const updateData: { [key: string]: any | undefined } = {};
userId: string,
updates: UpdateData,
) {
const updateData: { [key: string]: any | undefined } = {};
if (updates.username || updates.username != "") { if (updates.username || updates.username != "") {
updateData.username = updates.username; updateData.username = updates.username;
} }
if (updates.full_name || updates.full_name != "") { if (updates.full_name || updates.full_name != "") {
updateData.full_name = updates.full_name; updateData.full_name = updates.full_name;
} }
if (updates.bio || updates.bio != "") { if (updates.bio || updates.bio != "") {
updateData.bio = updates.bio; updateData.bio = updates.bio;
}
if (updates.avatar_url || updates.avatar_url != "") {
updateData.avatar_url = updates.avatar_url;
}
updateData.updated_at = new Date();
console.log(updateData);
if (
updateData.username != undefined ||
updateData.full_name != undefined ||
updateData.bio != undefined ||
updateData.avatar_url != undefined
) {
const { error } = await supabase.from("profiles").update(updateData).eq("id", userId);
if (error) {
throw error;
} }
updateData.updated_at = new Date(); return true;
} else {
if ( return null;
updateData.username != undefined || updateData.full_name != undefined || }
updateData.bio != undefined
) {
const { error } = await supabase
.from("profiles")
.update(updateData)
.eq("id", userId);
if (error) {
console.error("Error updating profile:", error);
throw error;
}
return true;
} else {
console.log("No fields to update.");
return null;
}
} }