Cancellation
A product search where the server takes 1.5 seconds to answer. Type a few letters quickly: every new letter cancels the search that is still running, and the log shows each request being sent and canceled. Cancel stops the current one.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useEffect, useState } from "react";
import { client } from "./api";
import type { SearchRequest } from "./api";
type Entry = { id: string; text: string; kind: "start" | "abort" | "done" };
/** Listens to the client's request events, so it sees every request, also the ones no component waits for anymore. */
export const RequestLog = () => {
const [entries, setEntries] = useState<Entry[]>([]);
useEffect(() => {
const { events } = client.requestManager;
const add = (kind: Entry["kind"], text: string) =>
setEntries((list) => [{ id: `${Date.now()}-${Math.random()}`, kind, text }, ...list].slice(0, 8));
const term = (request: SearchRequest) => `"${request.queryParams?.q ?? ""}"`;
const unmountStart = events.onRequestStart<SearchRequest>(({ request }) => add("start", `${term(request)} sent`));
const unmountAbort = events.onAbort<SearchRequest>(({ request }) => add("abort", `${term(request)} canceled`));
const unmountResponse = events.onResponse<SearchRequest>(({ request, response, details }) => {
if (details.isCanceled) return;
add("done", `${term(request)} answered with ${response.data?.total ?? 0} results`);
});
return () => {
unmountStart();
unmountAbort();
unmountResponse();
};
}, []);
return (
<article>
<header>
<strong>Request log</strong>
</header>
{entries.length === 0 && <p className="muted">Type to send requests.</p>}
<ol className="log">
{entries.map((entry) => (
<li key={entry.id} className={entry.kind}>
{entry.text}
</li>
))}
</ol>
</article>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/cancellation hyper-fetch-react-cancellation && cd hyper-fetch-react-cancellation && npm install && npm run devcancelable: true: a new request aborts the running one in the same queue, so a slow old answer never replaces a newer one.- A shared
queryKeyputs searches with different query params in one queue. abort()fromuseFetchcancels the request the hook is waiting for.- Request events:
client.requestManager.eventsreports every start, abort and response.
How it works
-
searchProductsRequestis created with two options:{endpoint: "/products/search",cancelable: true,queryKey: "product-search",}The dispatcher groups requests by
queryKey. By default it is built from the endpoint and the query params, so?q=phand?q=phowould sit in different queues and never cancel each other. A fixedqueryKeyputs them together. The cache key still includes the query params, so every term is cached on its own. -
AppcallsuseFetch(searchProductsRequest.setQueryParams({ q: query, ... })). Each keystroke changes the query params and adds a new request. Because the request is cancelable, the dispatcher aborts the running one first. -
Cancel calls
abort(). The request is aborted and the hook gets an error response with the messageRequest aborted;send()and the hooks never throw for it. -
RequestLogsubscribes toonRequestStart,onAbortandonResponseonclient.requestManager.events. A canceled request also emits a response, withdetails.isCanceledset, which the log skips.
For search inputs you can combine this with the bounce option of useFetch to send fewer requests in the first place.
Cancellation still matters then: a request that already started can be outrun by the next one.
- Search, filters and pagination, where only the latest answer matters.
- Long requests the user may give up on, such as reports or exports.
Related
A cancelable request aborts the previous one in its queue, and a shared queryKey decides which requests share that
queue. abort() from a hook cancels the current request on demand.
