NGU-Web/src/lib/useResource.ts
Zaldimmar 222c9e69a2 Third audit, UI half; side nav on top; request button colors
- Event cards: lazy -640 photo, only nearby slides drawn, a counter
  past 12 events, past grid paged with Show more
- Community map: search over list and grid, 12 per region then Show
  all, list no longer redrawn on hover
- People tiles: one clip check for the list, Show all past 30
- Person pages: 6 events and posts then Show all; excerpts load only
  the first paragraph
- Admin: filter box on long pickers and the QR select, options sent
  per form, Media thumbnails from the small copy, debounced searches
  that drop stale answers
- Pages show their last data while refreshing after the cache TTL
- Side nav stacks above page content (the carousel arrows)
- No event request button on National Retreats; request buttons take
  their section's accent
- Version v1.11.1-audit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 19:09:21 -05:00

51 lines
1.7 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
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.
A path asked for before starts from its last answer (api.ts,
peek) and isn't `loading` while it refreshes, so a page opened
again after the TTL doesn't flash its skeleton.
═══════════════════════════════════════════════════════════════ */
import { useEffect, useState } from "react";
import { get, peek } from "./api.ts";
export function useResource(path, { ttl }: { ttl?: number } = {}) {
const [state, setState] = useState<any>(() => {
const stale = peek(path);
return { data: stale, error: null, loading: stale === undefined };
});
useEffect(() => {
let ignore = false;
const stale = peek(path);
setState((prev) =>
stale === undefined
? { ...prev, loading: true, error: null }
: { data: stale, error: null, loading: false },
);
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;
}