Some checks failed
Deploy to Test Environment / deploy-to-test (push) Failing after 1m1s
49 lines
1.5 KiB
TypeScript
49 lines
1.5 KiB
TypeScript
// src/hooks/queries/useFlyerItemCountQuery.ts
|
|
import { useQuery } from '@tanstack/react-query';
|
|
import { countFlyerItemsForFlyers } from '../../services/apiClient';
|
|
|
|
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: ['flyer-items-count', flyerIds.sort().join(',')],
|
|
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');
|
|
}
|
|
|
|
return response.json();
|
|
},
|
|
enabled: enabled && flyerIds.length > 0,
|
|
// Count doesn't change frequently
|
|
staleTime: 1000 * 60 * 5, // 5 minutes
|
|
});
|
|
};
|