feat: Enahnce add item delay
This commit is contained in:
@@ -14,6 +14,15 @@ export const auth = betterAuth({
|
|||||||
baseURL: process.env.BETTER_AUTH_URL,
|
baseURL: process.env.BETTER_AUTH_URL,
|
||||||
secret: process.env.BETTER_AUTH_SECRET,
|
secret: process.env.BETTER_AUTH_SECRET,
|
||||||
trustedOrigins,
|
trustedOrigins,
|
||||||
|
session: {
|
||||||
|
// A signed copy of the session lives in a cookie for 5 minutes, so protected
|
||||||
|
// routes skip the session lookup in Postgres on every request. Trade-off: a
|
||||||
|
// session revoked elsewhere stays valid on other devices until the cache expires.
|
||||||
|
cookieCache: {
|
||||||
|
enabled: true,
|
||||||
|
maxAge: 5 * 60,
|
||||||
|
},
|
||||||
|
},
|
||||||
emailAndPassword: {
|
emailAndPassword: {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
minPasswordLength: 8,
|
minPasswordLength: 8,
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button'
|
|||||||
import { Field, FieldError } from '@/components/ui/field'
|
import { Field, FieldError } from '@/components/ui/field'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { useCreateItem } from '@/hooks/use-items'
|
import { useCreateItem } from '@/hooks/use-items'
|
||||||
|
import { ApiError } from '@/lib/api-client'
|
||||||
|
|
||||||
const createItemSchema = z.object({
|
const createItemSchema = z.object({
|
||||||
name: z.string().trim().min(1, 'Escribe un artículo').max(120, 'Máximo 120 caracteres'),
|
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: '' },
|
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) => {
|
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 (
|
return (
|
||||||
@@ -64,9 +78,9 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
<FieldError errors={[form.formState.errors.name]} />
|
<FieldError errors={[form.formState.errors.name]} />
|
||||||
</Field>
|
</Field>
|
||||||
|
|
||||||
<Button type="submit" disabled={createItem.isPending}>
|
<Button type="submit">
|
||||||
<PlusIcon />
|
<PlusIcon />
|
||||||
{createItem.isPending ? 'Agregando…' : 'Agregar'}
|
Agregar
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { ListItem } from '@superlist/shared'
|
|||||||
import { CheckIcon } from 'lucide-react'
|
import { CheckIcon } from 'lucide-react'
|
||||||
|
|
||||||
import { Card, CardContent } from '@/components/ui/card'
|
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'
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
type ItemRowProps = {
|
type ItemRowProps = {
|
||||||
@@ -19,7 +19,8 @@ export function ItemRow({ item, updateItem }: ItemRowProps) {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
aria-pressed={item.completed}
|
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 })}
|
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"
|
className="flex w-full cursor-pointer items-center gap-3 p-3 text-left disabled:cursor-default disabled:opacity-60"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -13,8 +13,17 @@ export function useItems(listId: string) {
|
|||||||
return useQuery(itemsQueryOptions(listId))
|
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) {
|
export function useCreateItem(listId: string) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
const { queryKey } = itemsQueryOptions(listId)
|
||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: (input: { name: string; quantity?: string; notes?: string }) =>
|
mutationFn: (input: { name: string; quantity?: string; notes?: string }) =>
|
||||||
@@ -22,7 +31,41 @@ export function useCreateItem(listId: string) {
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify(input),
|
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),
|
||||||
|
)
|
||||||
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user