import { useAuth } from '@components/auth/auth-provider'; import AvatarUser from '@components/avatar/avatar-user'; import RoleBadge from '@components/avatar/role-badge'; import { useAppForm } from '@hooks/use-app-form'; import { authClient } from '@lib/auth-client'; import { m } from '@paraglide/messages'; import { UserCircleIcon } from '@phosphor-icons/react'; import { uploadProfileImage } from '@service/profile.api'; import { ProfileInput, profileUpdateSchema } from '@service/profile.schema'; import { useQueryClient } from '@tanstack/react-query'; import { Card, CardContent, CardHeader, CardTitle } from '@ui/card'; import { Field, FieldGroup, FieldLabel } from '@ui/field'; import { Input } from '@ui/input'; import { useRef } from 'react'; import { toast } from 'sonner'; const defaultValues: ProfileInput = { name: '', image: undefined, }; const ProfileForm = () => { const fileInputRef = useRef(null); const { data: session, isPending } = useAuth(); const queryClient = useQueryClient(); const form = useAppForm({ defaultValues: { ...defaultValues, name: session?.user?.name || '', }, validators: { onSubmit: profileUpdateSchema, onChange: profileUpdateSchema, }, onSubmit: async ({ value }) => { try { let imageKey; if (value.image) { // upload image const formData = new FormData(); formData.set('file', value.image); const { imageKey: uploadedKey } = await uploadProfileImage({ data: formData, }); imageKey = uploadedKey; } await authClient.updateUser( { name: value.name, image: imageKey, }, { onSuccess: () => { form.reset(); if (fileInputRef.current) { fileInputRef.current.value = ''; } queryClient.refetchQueries({ queryKey: ['auth', 'session'], }); toast.success(m.profile_messages_update_success(), { richColors: true, }); }, onError: (ctx) => { console.error(ctx.error.code); toast.error(m.backend_message({ code: ctx.error.code }), { richColors: true, }); }, }, ); } catch (error) { console.error('update load file', error); toast.error(JSON.stringify(error), { richColors: true, }); } }, }); if (isPending) return null; if (!session?.user?.name) return null; return ( {m.profile_ui_title()}
{ e.preventDefault(); e.stopPropagation(); form.handleSubmit(); }} >
{(field) => ( field.handleChange(e.target.files?.[0])} /> )}
{(field) => } {m.profile_form_email()} {m.profile_form_role()}
); }; export default ProfileForm;