// src/hooks/queries/useFlyerItemsQuery.ts import { useQuery } from '@tanstack/react-query'; import * as apiClient from '../../services/apiClient'; import { queryKeys } from '../../config/queryKeys'; import type { FlyerItem } from '../../types'; /** * Query hook for fetching items for a specific flyer. * * This hook is automatically disabled when no flyer ID is provided, * and caches data per-flyer to avoid refetching the same data. * * @param flyerId - The ID of the flyer to fetch items for * @returns Query result with flyer items data, loading state, and error state * * @example * ```tsx * const { data: flyerItems, isLoading, error } = useFlyerItemsQuery(flyer?.flyer_id); * ``` */ export const useFlyerItemsQuery = (flyerId: number | undefined) => { return useQuery({ queryKey: queryKeys.flyerItems(flyerId as number), queryFn: async (): Promise => { if (!flyerId) { throw new Error('Flyer ID is required'); } const response = await apiClient.fetchFlyerItems(flyerId); 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'); } const json = await response.json(); // ADR-028: API returns { success: true, data: [...] } // If success is false or data is not an array, return empty array to prevent .map() errors if (!json.success || !Array.isArray(json.data)) { return []; } return json.data; }, // Only run the query if we have a valid flyer ID enabled: !!flyerId, // Flyer items don't change, so cache them longer staleTime: 1000 * 60 * 5, }); };