All files / src/hooks/queries useBestSalePricesQuery.ts

0% Statements 0/11
0% Branches 0/9
0% Functions 0/3
0% Lines 0/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                                                                                             
// src/hooks/queries/useBestSalePricesQuery.ts
import { useQuery } from '@tanstack/react-query';
import { fetchBestSalePrices } from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';
import type { WatchedItemDeal } from '../../types';
 
/**
 * Query hook for fetching the best sale prices for the user's watched items.
 *
 * Returns deals where watched items are currently on sale, sorted by best price.
 * This data is user-specific and requires authentication.
 *
 * @param enabled - Whether the query should run (typically based on auth status)
 * @returns Query result with best sale prices data, loading state, and error state
 *
 * @example
 * ```tsx
 * const { data: deals, isLoading, error } = useBestSalePricesQuery(!!user);
 * ```
 */
export const useBestSalePricesQuery = (enabled: boolean = true) => {
  return useQuery({
    queryKey: queryKeys.bestSalePrices(),
    queryFn: async (): Promise<WatchedItemDeal[]> => {
      const response = await fetchBestSalePrices();
 
      if (!response.ok) {
        const error = await response.json().catch(() => ({
          message: `Request failed with status ${response.status}`,
        }));
        throw new Error(error.message || 'Failed to fetch best sale prices');
      }
 
      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;
    },
    enabled,
    // Prices update when flyers change, keep fresh for 2 minutes
    staleTime: 1000 * 60 * 2,
  });
};