All files / src/hooks/queries useFlyerItemCountQuery.ts

9.09% Statements 1/11
0% Branches 0/11
0% Functions 0/3
10% Lines 1/10

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                                                      
// src/hooks/queries/useFlyerItemCountQuery.ts
import { useQuery } from '@tanstack/react-query';
import { countFlyerItemsForFlyers } from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';
 
interface FlyerItemCount {
  count: number;
}
 
/**
 * Query hook for counting total flyer items across multiple flyers.
 *
 * This is used to display the total number of active deals available.
 *
 * @param flyerIds - Array of flyer IDs to count items for
 * @param enabled - Whether the query should run
 * @returns Query result with count data
 *
 * @example
 * ```tsx
 * const { data } = useFlyerItemCountQuery(validFlyerIds, validFlyerIds.length > 0);
 * const totalItems = data?.count ?? 0;
 * ```
 */
export const useFlyerItemCountQuery = (flyerIds: number[], enabled: boolean = true) => {
  return useQuery({
    // Include flyerIds in the key so cache is per-set of flyers
    queryKey: queryKeys.flyerItemsCount(flyerIds),
    queryFn: async (): Promise<FlyerItemCount> => {
      if (flyerIds.length === 0) {
        return { count: 0 };
      }
 
      const response = await countFlyerItemsForFlyers(flyerIds);
 
      if (!response.ok) {
        const error = await response.json().catch(() => ({
          message: `Request failed with status ${response.status}`,
        }));
        throw new Error(error.message || 'Failed to count flyer items');
      }
 
      const json = await response.json();
      // API returns { success: true, data: {...} }, extract the data object
      return json.data ?? json;
    },
    enabled: enabled && flyerIds.length > 0,
    // Count doesn't change frequently
    staleTime: 1000 * 60 * 5, // 5 minutes
  });
};