All files / src/hooks/queries useShoppingListsQuery.ts

100% Statements 11/11
100% Branches 8/8
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 463x     6x   6x 3x     3x     3x     3x 1x   2x              
// src/hooks/queries/useShoppingListsQuery.ts
import { useQuery } from '@tanstack/react-query';
import * as apiClient from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';
import type { ShoppingList } from '../../types';
 
/**
 * Query hook for fetching the user's shopping lists.
 *
 * This hook is automatically disabled when the user is not authenticated,
 * and the cached data is invalidated when the user logs out.
 *
 * @param enabled - Whether the query should run (typically based on auth status)
 * @returns Query result with shopping lists data, loading state, and error state
 *
 * @example
 * ```tsx
 * const { data: shoppingLists, isLoading, error } = useShoppingListsQuery(!!user);
 * ```
 */
export const useShoppingListsQuery = (enabled: boolean) => {
  return useQuery({
    queryKey: queryKeys.shoppingLists(),
    queryFn: async (): Promise<ShoppingList[]> => {
      const response = await apiClient.fetchShoppingLists();
 
      if (!response.ok) {
        const error = await response.json().catch(() => ({
          message: `Request failed with status ${response.status}`,
        }));
        throw new Error(error.message || 'Failed to fetch shopping lists');
      }
 
      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,
    // Keep data fresh for 1 minute since users actively manage shopping lists
    staleTime: 1000 * 60,
  });
};