import { useEffect, useSyncExternalStore } from "react"; import { api, type UptimeReport } from "../api/client"; // One report for every ribbon on a page: the first to appear fetches it, the rest share it, and it is fetched again after a few minutes. const STALE_MS = 5 * 60_000; let report: UptimeReport | null = null; let fetchedAt = 0; let loading = false; const listeners = new Set<() => void>(); function load(): void { if (loading || (report && Date.now() - fetchedAt < STALE_MS)) return; loading = true; api.uptime .get() .then((r) => { report = r; fetchedAt = Date.now(); listeners.forEach((l) => l()); }) .catch(() => { // No ribbons rather than an error on every row: this is a nicety on top of the lists. }) .finally(() => { loading = false; }); } function subscribe(listener: () => void): () => void { listeners.add(listener); return () => { listeners.delete(listener); }; } /** How each server and integration has done over the last 30 days; null until it has loaded (or if it couldn't). */ export function useUptime(): UptimeReport | null { useEffect(load, []); return useSyncExternalStore(subscribe, () => report); }