/* ═══════════════════════════════════════════════════════════════ useResource The read hook every page uses: const { data, error, loading } = useResource("/events"); Note the `ignore` flag rather than an AbortController: the request is shared and cached, so canceling it would throw away work another component may still want. We just stop writing state after unmount. ═══════════════════════════════════════════════════════════════ */ import { useEffect, useState } from "react"; import { get } from "./api.ts"; export function useResource(path, { ttl }: { ttl?: number } = {}) { const [state, setState] = useState({ data: undefined, error: null, loading: true }); useEffect(() => { let ignore = false; setState((prev) => ({ ...prev, loading: true, error: null })); get(path, { ttl }) .then((data) => { if (!ignore) setState({ data, error: null, loading: false }); }) .catch((error) => { if (!ignore) setState((prev) => ({ ...prev, error, loading: false })); }); return () => { ignore = true; }; }, [path, ttl]); return state; }