Async data hook that aborts stale requests and supports refresh
A flight-tracker screen shows the details of the flight the user picked. The details come from an async call, the user can switch flights faster than the server answers, and a “Refresh” button fetches the current flight again. Writing this with useEffect each time leads to the same bugs: a slow old response overwrites the new one, the list flashes empty on every refresh, and requests keep running after the screen closes. Implement a React hook, useAsyncResource, that gets it right once.
function useAsyncResource<T>(
loader: (signal: AbortSignal) => Promise<T>,
deps: unknown[],
): {
status: 'loading' | 'success' | 'error';
data: T | undefined;
error: unknown;
reload: () => void;
}
loader: starts one request and returns a promise. It receives an AbortSignal that you abort when the request is no longer needed.deps: the values the request depends on, compared like useEffect dependencies.loader once with a new AbortSignal. The first render already returns status: 'loading'.status to 'success' and data to the value. When it rejects, set status to 'error' and error to the rejection reason.loader throws synchronously instead of returning a promise, treat the thrown value as a rejection. Do not let it crash the component.deps changes, start a new request. reload() also starts a new request with the same deps.status is 'loading' and error is undefined, but data keeps the last successful value so the screen does not flash empty. After an error, data also keeps the last successful value.loader as an inline function, so it is new on every render. A new loader alone must not start a request. When a request does start (deps change or reload()), use the latest loader.reload keeps the same identity on every render.function FlightDetails({ flightId }) {
const { status, data, error, reload } = useAsyncResource(
(signal) => fetch(`/api/flights/${flightId}`, { signal }).then((r) => r.json()),
[flightId],
);
if (status === 'error') return <p>Could not load {flightId}: {error.message}</p>;
return (
<section>
{status === 'loading' && <p>Updating…</p>}
{data && <h2>{data.code}: {data.gate}</h2>}
<button onClick={reload}>Refresh</button>
</section>
);
}
// flightId: 'UA90' -> status 'loading', data undefined
// UA90 resolves -> status 'success', data { code: 'UA90', gate: 'B12' }
// flightId: 'LH441' -> status 'loading', data still the UA90 object, UA90 signal not aborted (it settled)
// flightId: 'AF22' before LH441 answers -> the LH441 signal is aborted and its answer is ignored
reload() calls happen inside ReactDOM.flushSync. The tests then wait for React to re-render before reading the result.Object.assign(window, { useAsyncResource }); below “Do not edit below this line”. The tests use it to call your hook.