import { useState } from 'react'; import { useSuspenseQuery } from '@tanstack/react-query'; import { createFileRoute } from '@tanstack/react-router'; import { BIO_MAX_LENGTH, NAME_MAX_LENGTH, USERNAME_MAX_LENGTH, USERNAME_MIN_LENGTH, updateProfileSchema, } from '@repo/contracts'; import { Alert, AlertDescription } from '@repo/ui/components/alert'; import { Button } from '@repo/ui/components/button'; import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel, } from '@repo/ui/components/field'; import { Input } from '@repo/ui/components/input'; import { Separator } from '@repo/ui/components/separator'; import { Spinner } from '@repo/ui/components/spinner'; import { Textarea } from '@repo/ui/components/textarea'; import { toast } from '@repo/ui/components/toast'; import { NotificationSettings } from '@/components/notification-settings'; import { ApiError } from '@/lib/api'; import { ownProfileQuery, useUpdateProfile } from '@/lib/profile'; export const Route = createFileRoute('/app/settings')({ component: ProfileSettings, }); type FieldName = 'name' | 'username' | 'bio'; type FieldErrors = Partial>; function ProfileSettings() { const { data: profile } = useSuspenseQuery(ownProfileQuery); const updateProfile = useUpdateProfile(); const [fieldErrors, setFieldErrors] = useState({}); const [formError, setFormError] = useState(null); function handleSubmit(event: React.FormEvent) { event.preventDefault(); const form = new FormData(event.currentTarget); const parsed = updateProfileSchema.safeParse({ name: form.get('name'), username: form.get('username'), bio: form.get('bio'), }); setFormError(null); if (!parsed.success) { const errors: FieldErrors = {}; for (const issue of parsed.error.issues) { const field = issue.path[0] as FieldName; errors[field] ??= issue.message; } setFieldErrors(errors); return; } setFieldErrors({}); updateProfile.mutate(parsed.data, { onSuccess: () => { toast.add({ title: 'Profile saved', type: 'success' }); }, onError: (error) => { // 409 is the API's answer for a username someone else has. if (error instanceof ApiError && error.status === 409) { setFieldErrors({ username: error.message }); } else if (error instanceof ApiError) { setFormError(error.message); } else { setFormError('Could not save your profile. Please try again.'); } }, }); } return (

Profile

How you appear to other people.

{profile.username === null && ( Choose a username to finish setting up your account. )} {/* Remounts with the saved values, e.g. a username the API lower-cased. */}
Name {fieldErrors.name} Username How friends find you. Letters, numbers, underscores and dots. {fieldErrors.username} Bio