feat: Enahnce add item delay
This commit is contained in:
@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button'
|
||||
import { Field, FieldError } from '@/components/ui/field'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { useCreateItem } from '@/hooks/use-items'
|
||||
import { ApiError } from '@/lib/api-client'
|
||||
|
||||
const createItemSchema = z.object({
|
||||
name: z.string().trim().min(1, 'Escribe un artículo').max(120, 'Máximo 120 caracteres'),
|
||||
@@ -46,8 +47,21 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
defaultValues: { name: '' },
|
||||
})
|
||||
|
||||
// The input clears at once (the item is added optimistically) so several items
|
||||
// can be typed in a row; if the request fails the text comes back with the error.
|
||||
const onSubmit = form.handleSubmit((values) => {
|
||||
createItem.mutate(values, { onSuccess: () => form.reset() })
|
||||
form.reset()
|
||||
createItem.mutate(values, {
|
||||
onError: (error) => {
|
||||
form.setValue('name', values.name)
|
||||
form.setError('name', {
|
||||
message:
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos añadir el artículo.',
|
||||
})
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
return (
|
||||
@@ -64,9 +78,9 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
<FieldError errors={[form.formState.errors.name]} />
|
||||
</Field>
|
||||
|
||||
<Button type="submit" disabled={createItem.isPending}>
|
||||
<Button type="submit">
|
||||
<PlusIcon />
|
||||
{createItem.isPending ? 'Agregando…' : 'Agregar'}
|
||||
Agregar
|
||||
</Button>
|
||||
</form>
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user