All files / src/hooks/queries useFlyersQuery.ts

100% Statements 11/11
100% Branches 10/10
100% Functions 3/3
100% Lines 10/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                                          38x 329x     220x   220x 3x     3x     115x     115x 1x   114x            
// src/hooks/queries/useFlyersQuery.ts
import { useQuery } from '@tanstack/react-query';
import * as apiClient from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';
import type { Flyer } from '../../types';
 
/**
 * Query hook for fetching flyers with pagination.
 *
 * This replaces the custom useInfiniteQuery hook with TanStack Query,
 * providing automatic caching, background refetching, and better state management.
 *
 * @param limit - Maximum number of flyers to fetch
 * @param offset - Number of flyers to skip
 * @returns Query result with flyers data, loading state, and error state
 *
 * @example
 * ```tsx
 * const { data: flyers, isLoading, error, refetch } = useFlyersQuery(20, 0);
 * ```
 */
export const useFlyersQuery = (limit: number = 20, offset: number = 0) => {
  return useQuery({
    queryKey: queryKeys.flyers(limit, offset),
    queryFn: async (): Promise<Flyer[]> => {
      const response = await apiClient.fetchFlyers(limit, offset);
 
      if (!response.ok) {
        const error = await response.json().catch(() => ({
          message: `Request failed with status ${response.status}`,
        }));
        throw new Error(error.message || 'Failed to fetch flyers');
      }
 
      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;
    },
    // Keep data fresh for 2 minutes since flyers don't change frequently
    staleTime: 1000 * 60 * 2,
  });
};