// src/hooks/useWatchedItems.tsx import { useMemo, useCallback } from 'react'; import { useAuth } from '../hooks/useAuth'; import { useUserData } from '../hooks/useUserData'; import { useAddWatchedItemMutation, useRemoveWatchedItemMutation } from './mutations'; import { logger } from '../services/logger.client'; /** * A custom hook to manage all state and logic related to a user's watched items. * * This hook has been refactored to use TanStack Query mutations (ADR-0005 Phase 4). * It provides a simplified interface for adding and removing watched items with: * - Automatic cache invalidation * - Success/error notifications * - No manual state management * * The interface remains backward compatible with the previous implementation. */ const useWatchedItemsHook = () => { const { userProfile } = useAuth(); const { watchedItems } = useUserData(); // TanStack Query mutation hooks const addWatchedItemMutation = useAddWatchedItemMutation(); const removeWatchedItemMutation = useRemoveWatchedItemMutation(); // Consolidate errors from both mutations const error = useMemo(() => { const addErr = addWatchedItemMutation.error; const removeErr = removeWatchedItemMutation.error; return addErr?.message || removeErr?.message || null; }, [addWatchedItemMutation.error, removeWatchedItemMutation.error]); /** * Add an item to the watched items list. * Uses TanStack Query mutation which automatically invalidates the cache. */ const addWatchedItem = useCallback( async (itemName: string, category_id: number) => { if (!userProfile) return; try { await addWatchedItemMutation.mutateAsync({ itemName, category_id }); } catch (error) { // Error is already handled by the mutation hook (notification shown) // Just log for debugging logger.error({ err: error }, '[useWatchedItems] Failed to add item'); } }, [userProfile, addWatchedItemMutation], ); /** * Remove an item from the watched items list. * Uses TanStack Query mutation which automatically invalidates the cache. */ const removeWatchedItem = useCallback( async (masterItemId: number) => { if (!userProfile) return; try { await removeWatchedItemMutation.mutateAsync({ masterItemId }); } catch (error) { // Error is already handled by the mutation hook (notification shown) // Just log for debugging logger.error({ err: error }, '[useWatchedItems] Failed to remove item'); } }, [userProfile, removeWatchedItemMutation], ); return { watchedItems, addWatchedItem, removeWatchedItem, error, }; }; export { useWatchedItemsHook as useWatchedItems };