The PATCH endpoint now accepts quantity alongside completed (at least one field is required), and the row shows the quantity only when its leading number is above one. A small dialog edits it, opened by a left swipe on touch or by right-clicking the row on desktop.
161 lines
5.3 KiB
TypeScript
161 lines
5.3 KiB
TypeScript
import type { ListItem } from '@superlist/shared'
|
|
import {
|
|
queryOptions,
|
|
useMutation,
|
|
useMutationState,
|
|
useQuery,
|
|
useQueryClient,
|
|
} from '@tanstack/react-query'
|
|
|
|
import { toast } from 'sonner'
|
|
|
|
import { ApiError, apiFetch } from '@/lib/api-client'
|
|
|
|
export const itemsQueryOptions = (listId: string) =>
|
|
queryOptions({
|
|
queryKey: ['lists', listId, 'items'],
|
|
queryFn: () => apiFetch<ListItem[]>(`/lists/${listId}/items`),
|
|
})
|
|
|
|
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 }) =>
|
|
apiFetch<ListItem>(`/lists/${listId}/items`, {
|
|
method: 'POST',
|
|
body: JSON.stringify(input),
|
|
}),
|
|
// 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),
|
|
)
|
|
},
|
|
})
|
|
}
|
|
|
|
type UpdateItemInput = {
|
|
itemId: string
|
|
/** New bought state; omitted when only the quantity is being changed. */
|
|
completed?: boolean
|
|
/** New quantity (`null` clears it); omitted when only the bought state changes. */
|
|
quantity?: string | null
|
|
}
|
|
|
|
const updateItemMutationKey = (listId: string) => ['lists', listId, 'items', 'update']
|
|
|
|
export function useUpdateItem(listId: string) {
|
|
const queryClient = useQueryClient()
|
|
const { queryKey } = itemsQueryOptions(listId)
|
|
const mutationKey = updateItemMutationKey(listId)
|
|
|
|
return useMutation({
|
|
mutationKey,
|
|
mutationFn: (input: UpdateItemInput) => {
|
|
const body: { completed?: boolean; quantity?: string | null } = {}
|
|
if (input.completed !== undefined) body.completed = input.completed
|
|
if (input.quantity !== undefined) body.quantity = input.quantity
|
|
|
|
return apiFetch<ListItem>(`/lists/${listId}/items/${input.itemId}`, {
|
|
method: 'PATCH',
|
|
body: JSON.stringify(body),
|
|
})
|
|
},
|
|
onMutate: async ({ itemId, completed, quantity }) => {
|
|
// Cancel the outgoing refetch so it cannot overwrite our optimistic one.
|
|
await queryClient.cancelQueries({ queryKey })
|
|
|
|
const previous = queryClient.getQueryData(queryKey)?.find((item) => item.id === itemId)
|
|
|
|
queryClient.setQueryData(queryKey, (items) =>
|
|
items?.map((item) => {
|
|
if (item.id !== itemId) return item
|
|
|
|
return {
|
|
...item,
|
|
...(completed !== undefined
|
|
? { completed, boughtAt: completed ? new Date().toISOString() : null }
|
|
: {}),
|
|
...(quantity !== undefined ? { quantity: quantity?.trim() || null } : {}),
|
|
}
|
|
}),
|
|
)
|
|
|
|
return { previous }
|
|
},
|
|
// Only this item is rolled back, so other toggles in flight keep their state.
|
|
onError: (error, _variables, context) => {
|
|
toast.error(
|
|
error instanceof ApiError
|
|
? (error.problem.detail ?? error.problem.title)
|
|
: 'No pudimos guardar el cambio.',
|
|
)
|
|
|
|
const previous = context?.previous
|
|
if (!previous) return
|
|
|
|
queryClient.setQueryData(queryKey, (items) =>
|
|
items?.map((item) => (item.id === previous.id ? previous : item)),
|
|
)
|
|
},
|
|
// Several items can be toggled in a row: refetch once the last one settles, so an
|
|
// early refetch cannot bring back the server state of a toggle still in flight.
|
|
onSettled: () => {
|
|
if (queryClient.isMutating({ mutationKey }) === 1) {
|
|
return queryClient.invalidateQueries({ queryKey })
|
|
}
|
|
},
|
|
})
|
|
}
|
|
|
|
/** Ids of the items of a list whose bought state is being saved right now. */
|
|
export function usePendingItemUpdates(listId: string): string[] {
|
|
return useMutationState({
|
|
filters: { mutationKey: updateItemMutationKey(listId), status: 'pending' },
|
|
select: (mutation) => (mutation.state.variables as UpdateItemInput).itemId,
|
|
})
|
|
}
|