frontend: introduce custom stale timing for each type of insight
Parents:
df8bcbc1 file(s) changed
- frontend/hooks/useInsights.queries.ts +25 -11
frontend/hooks/useInsights.queries.ts
1 1
import { useQuery } from "@tanstack/react-query";
2 2
import { apiClient, Insight, InsightType, InsightPeriod } from "@/lib/api";
3 3
4 4
export const insightKeys = {
5 5
all: () => ["insights"] as const,
▸ 7 unchanged lines
13 13
type?: InsightType;
14 14
period?: InsightPeriod;
15 15
limit?: number;
16 16
}
17 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 -
});
18 +
const INSIGHT_STALE_TIMES: Record<InsightPeriod, number> = {
19 +
DAILY: 1000 * 60 * 30, // 30 min, regenerates during the day
20 +
WEEKLY: 1000 * 60 * 60 * 4, // 4h only changes on cron or mutations
21 +
MONTHLY: 1000 * 60 * 60 * 24, // 24h
25 22
};
26 23
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
24 +
const INSIGHT_PERIOD: Record<InsightType, InsightPeriod> = {
25 +
DAILY_ENERGY: "DAILY",
26 +
MOOD_TREND: "WEEKLY",
27 +
ENERGY_SLEEP_CORRELATION: "WEEKLY",
28 +
TRIGGER_PATTERN: "WEEKLY",
29 +
};
30 +
30 31
export const useInsight = (type: InsightType) => {
32 +
const period = INSIGHT_PERIOD[type];
33 +
const staleTime = INSIGHT_STALE_TIMES[period];
34 +
31 35
return useQuery({
32 36
queryKey: insightKeys.byType(type),
33 37
queryFn: () =>
34 -
apiClient.getInsights({ type, limit: 1 }).then((res) => res[0] ?? null),
38 +
apiClient
39 +
.getInsights({ type, limit: 1 })
40 +
.then((res) => res.insights[0] ?? null),
41 +
staleTime,
42 +
});
43 +
};
44 +
45 +
export const useInsights = (filters?: InsightFilters) => {
46 +
return useQuery({
47 +
queryKey: insightKeys.list(filters),
48 +
queryFn: () => apiClient.getInsights(filters).then((res) => res.insights),
35 49
staleTime: 1000 * 60 * 15,
36 50
});
37 51
};