Files
flyer-crawler.projectium.com/src/hooks/mutations/useAddWatchedItemMutation.ts
Torben Sorensen 74a5ca6331
All checks were successful
Deploy to Test Environment / deploy-to-test (push) Successful in 24m33s
claude 1 - fixes : -/
2026-01-08 22:30:21 -08:00

61 lines
1.8 KiB
TypeScript

// src/hooks/mutations/useAddWatchedItemMutation.ts
import { useMutation, useQueryClient } from '@tanstack/react-query';
import * as apiClient from '../../services/apiClient';
import { notifySuccess, notifyError } from '../../services/notificationService';
interface AddWatchedItemParams {
itemName: string;
category?: string;
}
/**
* Mutation hook for adding an item to the user's watched items list.
*
* This hook provides optimistic updates and automatic cache invalidation.
* When the mutation succeeds, it invalidates the watched-items query to
* trigger a refetch of the updated list.
*
* @returns Mutation object with mutate function and state
*
* @example
* ```tsx
* const addWatchedItem = useAddWatchedItemMutation();
*
* const handleAdd = () => {
* addWatchedItem.mutate(
* { itemName: 'Milk', category: 'Dairy' },
* {
* onSuccess: () => console.log('Added!'),
* onError: (error) => console.error(error),
* }
* );
* };
* ```
*/
export const useAddWatchedItemMutation = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ itemName, category }: AddWatchedItemParams) => {
const response = await apiClient.addWatchedItem(itemName, category ?? '');
if (!response.ok) {
const error = await response.json().catch(() => ({
message: `Request failed with status ${response.status}`,
}));
throw new Error(error.message || 'Failed to add watched item');
}
return response.json();
},
onSuccess: () => {
// Invalidate and refetch watched items to get the updated list
queryClient.invalidateQueries({ queryKey: ['watched-items'] });
notifySuccess('Item added to watched list');
},
onError: (error: Error) => {
notifyError(error.message || 'Failed to add item to watched list');
},
});
};