eletrotupi / tcc/ frontend/hooks/useInsights.queries.tsfe2deb48e4d91c97820de01dec6dd464c725329f
1.2 KB | 37 lines Raw
1
import { useQuery } from "@tanstack/react-query";
2
import { apiClient, Insight, InsightType, InsightPeriod } from "@/lib/api";
3

4
export const insightKeys = {
5
  all: () => ["insights"] as const,
6
  lists: () => [...insightKeys.all(), "list"] as const,
7
  list: (filters?: InsightFilters) =>
8
    [...insightKeys.lists(), filters] as const,
9
  byType: (type: InsightType) => [...insightKeys.all(), "type", type] as const,
10
};
11

12
interface InsightFilters {
13
  type?: InsightType;
14
  period?: InsightPeriod;
15
  limit?: number;
16
}
17

18
// All insights — for the insights page
19
export const useInsights = (filters?: InsightFilters) => {
20
  return useQuery({
21
    queryKey: insightKeys.list(filters),
22
    queryFn: () => apiClient.getInsights(filters),
23
    staleTime: 1000 * 60 * 15,
24
  });
25
};
26

27
// Single type — for widgets that only care about one insight
28
// Each call caches independently, so mood log page doesn't blow
29
// away what the insights page already fetched
30
export const useInsight = (type: InsightType) => {
31
  return useQuery({
32
    queryKey: insightKeys.byType(type),
33
    queryFn: () =>
34
      apiClient.getInsights({ type, limit: 1 }).then((res) => res[0] ?? null),
35
    staleTime: 1000 * 60 * 15,
36
  });
37
};