feat(items): edit an item's quantity by swiping or right-clicking it
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.
This commit is contained in:
@@ -77,7 +77,13 @@ export function useCreateItem(listId: string) {
|
||||
})
|
||||
}
|
||||
|
||||
type UpdateItemInput = { itemId: string; completed: boolean }
|
||||
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']
|
||||
|
||||
@@ -88,23 +94,34 @@ export function useUpdateItem(listId: string) {
|
||||
|
||||
return useMutation({
|
||||
mutationKey,
|
||||
mutationFn: (input: UpdateItemInput) =>
|
||||
apiFetch<ListItem>(`/lists/${listId}/items/${input.itemId}`, {
|
||||
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({ completed: input.completed }),
|
||||
}),
|
||||
onMutate: async ({ itemId, completed }) => {
|
||||
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) =>
|
||||
item.id === itemId
|
||||
? { ...item, completed, boughtAt: completed ? new Date().toISOString() : null }
|
||||
: item,
|
||||
),
|
||||
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 }
|
||||
|
||||
Reference in New Issue
Block a user