/** * useAsyncResource (API §1.1) — a one-shot async read projected into the §1 read * envelope (`ReadState`): the non-memory sibling of `useRead`, stale-guarded and * `refetch`-able, with a `null` loader as idle. Shared by `application/` and the * window `useViewsFor` dispatch; homed here (below both) to keep rule 9 acyclic. */ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { ReadState } from './memory/read/envelope.js' export interface AsyncResource extends ReadState { readonly data: T } interface AsyncState { readonly data: T readonly pending: boolean readonly error: unknown } /** * Subscribe a component to `load()`. `null` loader → idle. The loader runs on * mount and whenever `deps` change (stale responses discarded); last-good data is * retained through a pending refetch or a failure (§1.1). */ export function useAsyncResource( load: (() => Promise) | null, empty: T, deps: readonly unknown[], ): AsyncResource { const [state, setState] = useState>({ data: empty, pending: load !== null, error: undefined, }) const loadRef = useRef(load) loadRef.current = load const emptyRef = useRef(empty) emptyRef.current = empty const seq = useRef(0) const alive = useRef(true) useEffect(() => { alive.current = true return () => { alive.current = false } }, []) const refetch = useCallback((): Promise => { const run = loadRef.current if (run === null) { setState({ data: emptyRef.current, pending: false, error: undefined }) return Promise.resolve() } const my = ++seq.current setState((s) => ({ data: s.data, pending: true, error: undefined })) return run().then( (data) => { if (alive.current && my === seq.current) setState({ data, pending: false, error: undefined }) }, (error: unknown) => { if (alive.current && my === seq.current) { setState((s) => ({ data: s.data, pending: false, error })) } }, ) }, []) useEffect(() => { void refetch() // eslint-disable-next-line react-hooks/exhaustive-deps }, deps) return useMemo( () => ({ data: state.data, pending: state.pending, error: state.error, live: false, seq: 0, refetch, }), [state.data, state.pending, state.error, refetch], ) }