// src/hooks/queries/useLeaderboardQuery.ts import { useQuery } from '@tanstack/react-query'; import { fetchLeaderboard } from '../../services/apiClient'; import { queryKeys } from '../../config/queryKeys'; import type { LeaderboardUser } from '../../types'; /** * Query hook for fetching the public leaderboard. * * @param limit - Number of top users to fetch (default: 10) * @param enabled - Whether the query should run (default: true) * @returns TanStack Query result with LeaderboardUser array * * @example * ```tsx * const { data: leaderboard = [], isLoading, error } = useLeaderboardQuery(10); * ``` */ export const useLeaderboardQuery = (limit: number = 10, enabled: boolean = true) => { return useQuery({ queryKey: queryKeys.leaderboard(limit), queryFn: async (): Promise => { const response = await fetchLeaderboard(limit); if (!response.ok) { const error = await response.json().catch(() => ({ message: `Request failed with status ${response.status}`, })); throw new Error(error.message || 'Failed to fetch leaderboard'); } 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, staleTime: 1000 * 60 * 2, // 2 minutes - leaderboard can change moderately }); };