// src/hooks/queries/useFlyerItemsForFlyersQuery.ts import { useQuery } from '@tanstack/react-query'; import { fetchFlyerItemsForFlyers } from '../../services/apiClient'; import { queryKeys } from '../../config/queryKeys'; import type { FlyerItem } from '../../types'; /** * Query hook for fetching flyer items for multiple flyers. * * This is used to get all items from currently valid flyers, * which are then filtered against the user's watched items to find deals. * * @param flyerIds - Array of flyer IDs to fetch items for * @param enabled - Whether the query should run * @returns Query result with flyer items data * * @example * ```tsx * const { data: items } = useFlyerItemsForFlyersQuery(validFlyerIds, validFlyerIds.length > 0); * ``` */ export const useFlyerItemsForFlyersQuery = (flyerIds: number[], enabled: boolean = true) => { return useQuery({ // Include flyerIds in the key so cache is per-set of flyers queryKey: queryKeys.flyerItemsBatch(flyerIds), queryFn: async (): Promise => { if (flyerIds.length === 0) { return []; } const response = await fetchFlyerItemsForFlyers(flyerIds); if (!response.ok) { const error = await response.json().catch(() => ({ message: `Request failed with status ${response.status}`, })); throw new Error(error.message || 'Failed to fetch flyer items'); } return response.json(); }, enabled: enabled && flyerIds.length > 0, // Flyer items don't change frequently once created staleTime: 1000 * 60 * 5, // 5 minutes }); };