Some checks failed
CI / Verify (push) Has been cancelled
API: lists, items and invitations modules (list, create, get, update, set-primary, items create/list, invitation create/accept/list-pending), BetterAuth session helper, list membership, mailer and Prisma schema plus migrations. Web: lists overview, list detail (items) and list management (settings) views, item and invitation forms/hooks, sign-up and invitation accept pages. Shared: shopping list DTOs. Tooling: ignore the generated TanStack Router cache (apps/web/.tanstack).
82 lines
2.4 KiB
TypeScript
82 lines
2.4 KiB
TypeScript
import { zodResolver } from '@hookform/resolvers/zod'
|
|
import { useState } from 'react'
|
|
import { useForm } from 'react-hook-form'
|
|
import { z } from 'zod'
|
|
|
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
|
|
import { Input } from '@/components/ui/input'
|
|
import { useCreateList } from '@/hooks/use-lists'
|
|
import { ApiError } from '@/lib/api-client'
|
|
|
|
const createListSchema = z.object({
|
|
name: z.string().trim().min(1, 'El nombre es obligatorio').max(80, 'Máximo 80 caracteres'),
|
|
})
|
|
|
|
type CreateListValues = z.infer<typeof createListSchema>
|
|
|
|
type CreateListFormProps = {
|
|
onCreated?: () => void
|
|
}
|
|
|
|
/** Inline form to create a shopping list. Used by the lists page. */
|
|
export function CreateListForm({ onCreated }: CreateListFormProps) {
|
|
const [error, setError] = useState<string | null>(null)
|
|
const createList = useCreateList()
|
|
|
|
const form = useForm<CreateListValues>({
|
|
resolver: zodResolver(createListSchema),
|
|
defaultValues: { name: '' },
|
|
})
|
|
|
|
const onSubmit = form.handleSubmit((values) => {
|
|
setError(null)
|
|
|
|
createList.mutate(values, {
|
|
onSuccess: () => {
|
|
form.reset()
|
|
onCreated?.()
|
|
},
|
|
onError: (mutationError) => {
|
|
setError(
|
|
mutationError instanceof ApiError
|
|
? (mutationError.problem.detail ?? mutationError.problem.title)
|
|
: 'No pudimos crear la lista.',
|
|
)
|
|
},
|
|
})
|
|
})
|
|
|
|
return (
|
|
<form onSubmit={onSubmit} className="flex flex-col gap-4">
|
|
{error && (
|
|
<Alert variant="destructive">
|
|
<AlertDescription>{error}</AlertDescription>
|
|
</Alert>
|
|
)}
|
|
|
|
<FieldGroup>
|
|
<Field data-invalid={!!form.formState.errors.name}>
|
|
<FieldLabel htmlFor="list-name">Nombre de la lista</FieldLabel>
|
|
<Input
|
|
id="list-name"
|
|
placeholder="Compra semanal"
|
|
autoComplete="off"
|
|
{...form.register('name')}
|
|
/>
|
|
<FieldError errors={[form.formState.errors.name]} />
|
|
</Field>
|
|
|
|
<Button
|
|
type="submit"
|
|
className="w-full sm:w-auto sm:self-start"
|
|
disabled={createList.isPending}
|
|
>
|
|
{createList.isPending ? 'Creando…' : 'Crear lista'}
|
|
</Button>
|
|
</FieldGroup>
|
|
</form>
|
|
)
|
|
}
|