All checks were successful
Deploy to Test Environment / deploy-to-test (push) Successful in 13m46s
60 lines
1.9 KiB
TypeScript
60 lines
1.9 KiB
TypeScript
// src/hooks/mutations/useRemoveShoppingListItemMutation.ts
|
|
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
|
import * as apiClient from '../../services/apiClient';
|
|
import { notifySuccess, notifyError } from '../../services/notificationService';
|
|
import { queryKeyBases } from '../../config/queryKeys';
|
|
|
|
interface RemoveShoppingListItemParams {
|
|
itemId: number;
|
|
}
|
|
|
|
/**
|
|
* Mutation hook for removing an item from a shopping list.
|
|
*
|
|
* This hook provides automatic cache invalidation. When the mutation succeeds,
|
|
* it invalidates the shopping-lists query to trigger a refetch of the updated list.
|
|
*
|
|
* @returns Mutation object with mutate function and state
|
|
*
|
|
* @example
|
|
* ```tsx
|
|
* const removeShoppingListItem = useRemoveShoppingListItemMutation();
|
|
*
|
|
* const handleRemove = (itemId: number) => {
|
|
* removeShoppingListItem.mutate(
|
|
* { itemId },
|
|
* {
|
|
* onSuccess: () => console.log('Removed!'),
|
|
* onError: (error) => console.error(error),
|
|
* }
|
|
* );
|
|
* };
|
|
* ```
|
|
*/
|
|
export const useRemoveShoppingListItemMutation = () => {
|
|
const queryClient = useQueryClient();
|
|
|
|
return useMutation({
|
|
mutationFn: async ({ itemId }: RemoveShoppingListItemParams) => {
|
|
const response = await apiClient.removeShoppingListItem(itemId);
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json().catch(() => ({
|
|
message: `Request failed with status ${response.status}`,
|
|
}));
|
|
throw new Error(error.message || 'Failed to remove shopping list item');
|
|
}
|
|
|
|
return response.json();
|
|
},
|
|
onSuccess: () => {
|
|
// Invalidate and refetch shopping lists to get the updated list
|
|
queryClient.invalidateQueries({ queryKey: queryKeyBases.shoppingLists });
|
|
notifySuccess('Item removed from shopping list');
|
|
},
|
|
onError: (error: Error) => {
|
|
notifyError(error.message || 'Failed to remove shopping list item');
|
|
},
|
|
});
|
|
};
|