import Image from "next/image"; import { t } from "@lingui/core/macro"; import { env } from "next-runtime-env"; import { useState } from "react"; import { generateUID } from "@kan/shared/utils"; import { usePopup } from "~/providers/popup"; import { api } from "~/utils/api"; import { getAvatarUrl } from "~/utils/helpers"; export default function Avatar({ userId, userImage, }: { userId: string | undefined; userImage: string | null | undefined; }) { const utils = api.useUtils(); const { showPopup } = usePopup(); const [uploading, setUploading] = useState(false); const updateUser = api.user.update.useMutation({ onSuccess: async () => { showPopup({ header: t`Profile image updated`, message: t`Your profile image has been updated.`, icon: "success", }); try { await utils.user.getUser.refetch(); } catch (e) { console.error(e); throw e; } }, onError: () => { showPopup({ header: t`Error updating profile image`, message: t`Please try again later, or contact customer support.`, icon: "error", }); }, }); const avatarUrl = userImage ? getAvatarUrl(userImage) : undefined; const uploadAvatar = async (event: React.ChangeEvent) => { try { event.preventDefault(); const file = event.target.files?.[0]; if (!file || !userId) { return showPopup({ header: t`Error uploading profile image`, message: t`Please select a file to upload.`, icon: "error", }); } const fileExt = file.name.split(".").pop(); const fileName = `${userId}/avatar-${generateUID()}.${fileExt}`; setUploading(true); const response = await fetch( env("NEXT_PUBLIC_BASE_URL") + "/api/upload/image", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ filename: fileName, contentType: file.type }), }, ); if (!response.ok) throw new Error("Failed to get pre-signed URL"); const { url } = (await response.json()) as { url: string; }; const uploadResponse = await fetch(url, { method: "PUT", body: file, }); if (!uploadResponse.ok) throw new Error("Failed to upload profile image"); updateUser.mutate({ image: fileName, }); } catch (error) { console.error(error); showPopup({ header: t`Error uploading profile image`, message: t`Please try again later, or contact customer support.`, icon: "error", }); } finally { setUploading(false); } }; return (
{avatarUrl ? ( Avatar ) : ( )}
); }