Skip to main content

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.

intermediateuseFetchcancellation
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>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/cancellation hyper-fetch-react-cancellation && cd hyper-fetch-react-cancellation && npm install && npm run dev
What it shows
  1. cancelable: true: a new request aborts the running one in the same queue, so a slow old answer never replaces a newer one.
  2. A shared queryKey puts searches with different query params in one queue.
  3. abort() from useFetch cancels the request the hook is waiting for.
  4. Request events: client.requestManager.events reports every start, abort and response.

How it works​

  1. searchProductsRequest is 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=ph and ?q=pho would sit in different queues and never cancel each other. A fixed queryKey puts them together. The cache key still includes the query params, so every term is cached on its own.

  2. App calls useFetch(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.

  3. Cancel calls abort(). The request is aborted and the hook gets an error response with the message Request aborted; send() and the hooks never throw for it.

  4. RequestLog subscribes to onRequestStart, onAbort and onResponse on client.requestManager.events. A canceled request also emits a response, with details.isCanceled set, 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.

When to use it
  • Search, filters and pagination, where only the latest answer matters.
  • Long requests the user may give up on, such as reports or exports.

Summary

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.