feat: Enahnce add item delay
This commit is contained in:
@@ -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),
|
||||
)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user