import { useEffect, useState } from "react"; import { api } from "../api/client"; import type { Catalog, MedsReference } from "../api/types"; /* * Static reference data from the server (questionnaire catalog, drug reference): fetched once per app run and * shared by every screen. A failed fetch is retried on the next mount; screens work without it, only less rich. */ function cached(load: () => Promise) { let value: T | null = null; let inflight: Promise | null = null; const get = () => { inflight ??= load().then( (v) => (value = v), (e) => { inflight = null; throw e; }, ); return inflight; }; return function useCached(): T | null { const [v, setV] = useState(value); useEffect(() => { if (value) return; let alive = true; get() .then((x) => alive && setV(x)) .catch(() => undefined); return () => { alive = false; }; }, []); return v; }; } export const useCatalog = cached(api.catalog); export const useMedsReference = cached(api.medsReference);