Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | 2x 13x 6x 6x 6x 3x 3x 3x 3x 1x 2x | // 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<FlyerItem[]> => {
Iif (!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,
});
};
|