feat: mark list items as bought on tap and record boughtAt
Tapping an item in the list toggles it via a new PATCH /lists/:listId/items/:itemId endpoint. Marking an item as bought stores boughtAt (for future stats) and clearing it back to pending resets the timestamp. The web app updates optimistically and each row is now a real button with aria-pressed.
This commit is contained in:
@@ -25,3 +25,38 @@ export function useCreateItem(listId: string) {
|
||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] }),
|
||||
})
|
||||
}
|
||||
|
||||
export function useUpdateItem(listId: string) {
|
||||
const queryClient = useQueryClient()
|
||||
const queryKey = ['lists', listId, 'items']
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (input: { itemId: string; completed: boolean }) =>
|
||||
apiFetch<ListItem>(`/lists/${listId}/items/${input.itemId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ completed: input.completed }),
|
||||
}),
|
||||
onMutate: async ({ itemId, completed }) => {
|
||||
// Cancel the outgoing refetch so it cannot overwrite our optimistic one.
|
||||
await queryClient.cancelQueries({ queryKey })
|
||||
|
||||
const previous = queryClient.getQueriesData<ListItem[]>({ queryKey })
|
||||
|
||||
queryClient.setQueriesData<ListItem[]>({ queryKey }, (items) =>
|
||||
items?.map((item) =>
|
||||
item.id === itemId
|
||||
? { ...item, completed, boughtAt: completed ? new Date().toISOString() : null }
|
||||
: item,
|
||||
),
|
||||
)
|
||||
|
||||
return { previous }
|
||||
},
|
||||
onError: (_error, _variables, context) => {
|
||||
context?.previous.forEach(([key, items]) => {
|
||||
queryClient.setQueryData(key, items)
|
||||
})
|
||||
},
|
||||
onSettled: () => queryClient.invalidateQueries({ queryKey }),
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user