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 | 1x 10x 5x 5x 3x 3x 2x 2x 2x | // src/hooks/queries/useCategoriesQuery.ts
import { useQuery } from '@tanstack/react-query';
import { fetchCategories } from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';
import type { Category } from '../../types';
/**
* Query hook for fetching all grocery categories.
*
* This is a public endpoint - no authentication required.
*
* Uses TanStack Query for automatic caching and refetching (ADR-0005 Phase 5).
*
* @returns TanStack Query result with Category[] data
*/
export const useCategoriesQuery = () => {
return useQuery({
queryKey: queryKeys.categories(),
queryFn: async (): Promise<Category[]> => {
const response = await fetchCategories();
if (!response.ok) {
const error = await response.json().catch(() => ({
message: `Request failed with status ${response.status}`,
}));
throw new Error(error.message || 'Failed to fetch categories');
}
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
Iif (!json.success || !Array.isArray(json.data)) {
return [];
}
return json.data;
},
staleTime: 1000 * 60 * 60, // 1 hour - categories rarely change
});
};
|