feat: Enahnce add item delay

This commit is contained in:
Jose Selesan
2026-10-19 12:26:21 -03:00
parent 815dcc300d
commit c374db1616
4 changed files with 73 additions and 6 deletions

View File

@@ -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>
)

View File

@@ -2,7 +2,7 @@ import type { ListItem } from '@superlist/shared'
import { CheckIcon } from 'lucide-react'
import { Card, CardContent } from '@/components/ui/card'
import type { useUpdateItem } from '@/hooks/use-items'
import { isOptimisticItem, type useUpdateItem } from '@/hooks/use-items'
import { cn } from '@/lib/utils'
type ItemRowProps = {
@@ -19,7 +19,8 @@ export function ItemRow({ item, updateItem }: ItemRowProps) {
<button
type="button"
aria-pressed={item.completed}
disabled={updateItem.isPending}
// A placeholder has no server id yet, so it cannot be toggled.
disabled={updateItem.isPending || isOptimisticItem(item)}
onClick={() => updateItem.mutate({ itemId: item.id, completed: !item.completed })}
className="flex w-full cursor-pointer items-center gap-3 p-3 text-left disabled:cursor-default disabled:opacity-60"
>

View File

@@ -13,8 +13,17 @@ export function useItems(listId: string) {
return useQuery(itemsQueryOptions(listId))
}
/** Prefix of the temporary ids given to items that are still being created. */
const OPTIMISTIC_ID_PREFIX = 'optimistic-'
/** Whether the item is a placeholder whose `POST` has not been answered yet. */
export function isOptimisticItem(item: ListItem): boolean {
return item.id.startsWith(OPTIMISTIC_ID_PREFIX)
}
export function useCreateItem(listId: string) {
const queryClient = useQueryClient()
const { queryKey } = itemsQueryOptions(listId)
return useMutation({
mutationFn: (input: { name: string; quantity?: string; notes?: string }) =>
@@ -22,7 +31,41 @@ export function useCreateItem(listId: string) {
method: 'POST',
body: JSON.stringify(input),
}),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] }),
// The item shows up right away; the POST response then swaps the placeholder
// for the real row, so no refetch of the whole list is needed (other members
// still get it through the SSE stream).
onMutate: async (input) => {
await queryClient.cancelQueries({ queryKey })
const now = new Date().toISOString()
const optimistic: ListItem = {
id: `${OPTIMISTIC_ID_PREFIX}${crypto.randomUUID()}`,
listId,
name: input.name.trim(),
completed: false,
boughtAt: null,
quantity: input.quantity?.trim() || null,
notes: input.notes?.trim() || null,
order: 0,
createdAt: now,
updatedAt: now,
}
queryClient.setQueryData(queryKey, (items) => items && [...items, optimistic])
return { optimisticId: optimistic.id }
},
onSuccess: (created, _input, context) => {
queryClient.setQueryData(queryKey, (items) =>
items?.map((item) => (item.id === context.optimisticId ? created : item)),
)
},
// Only this placeholder is removed, so other in-flight additions survive.
onError: (_error, _input, context) => {
queryClient.setQueryData(queryKey, (items) =>
items?.filter((item) => item.id !== context?.optimisticId),
)
},
})
}