// 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'); }, }); };