日本語

How to Add Both a Timeout and a Cancel Button to fetch in React

​​React​AbortController,AbortSignal,fetch,Playwright,TypeScript

To give fetch both a "timeout after 3 seconds" and a "cancel button", pass one signal to fetch that combines the cancel button's AbortController signal with AbortSignal.timeout(3000), using AbortSignal.any(). The request stops at whichever comes first. In React, I put this logic in a custom hook and kept the AbortController in a useRef, so the cancel button can call abort(). This works when you want a timeout that cuts off a slow API after a set time, and also want the user to be able to stop the request with a cancel button, both on the same request.

To find out why the request stopped (timeout or cancel button), read the reason from the combined signal's reason, not from the error passed to catch. In Chromium in my test environment, a timeout during body reading produced an error named AbortError, not TimeoutError, so it could not be told apart from the cancel button.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153 (headless). I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx with tsc, transformed it with esbuild, and ran the development build inside StrictMode. The API was a server I built with Node.js for testing. I did not test Firefox or Safari, the Node.js fetch, or the timeout behavior when a page enters the back/forward cache (bfcache).

Combining two signals with AbortSignal.any()

AbortSignal.timeout() returns a signal that aborts automatically after the given number of milliseconds. Its abort reason (reason) is a DOMException whose name is TimeoutError.

AbortSignal.any() returns a signal that aborts as soon as any one of the signals passed to it aborts. Its reason is the reason of the signal that aborted first. When abort() is called with no argument, as the cancel button does, the reason is a DOMException whose name is AbortError.

Using these, I wrote a custom hook that returns the state of the fetch.

ts
import { useEffect, useRef, useState } from 'react';

export type FetchState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'done'; text: string }
  | { status: 'timeout' }
  | { status: 'canceled' }
  | { status: 'error'; message: string };

export function useFetchWithCancel(timeoutMs: number) {
  const [state, setState] = useState<FetchState>({ status: 'idle' });
  const controllerRef = useRef<AbortController | null>(null);

  // Abort the in-flight request when the component unmounts
  useEffect(() => () => controllerRef.current?.abort(), []);

  async function start(url: string) {
    controllerRef.current?.abort(); // abort the previous request if one is still running
    const controller = new AbortController();
    controllerRef.current = controller;
    // Combine the cancel button's signal and the timeout signal into one
    const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]);
    setState({ status: 'loading' });
    try {
      const res = await fetch(url, { signal });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const text = await res.text();
      setState({ status: 'done', text });
    } catch (err) {
      if (controllerRef.current !== controller) return; // a newer request has taken over
      // Use signal.reason, not err, to find out why it stopped
      const reason = signal.aborted ? signal.reason : err;
      if (reason instanceof DOMException && reason.name === 'TimeoutError') {
        setState({ status: 'timeout' });
      } else if (reason instanceof DOMException && reason.name === 'AbortError') {
        setState({ status: 'canceled' });
      } else {
        setState({ status: 'error', message: String(err) });
      }
    } finally {
      if (controllerRef.current === controller) controllerRef.current = null;
    }
  }

  function cancel() {
    controllerRef.current?.abort();
  }

  return { state, start, cancel };
}

I create a new AbortController for each fetch and keep it in a useRef. cancel() just calls abort() on it. The AbortController is not a value used for display, so I store it in a useRef instead of state. Changing it does not cause a re-render.

I also create the timeout signal inside start() on every fetch. In my test environment, passing an already aborted signal (AbortSignal.abort()) to AbortSignal.any() returned a combined signal that was already aborted when it was created. So if you reuse a timeout signal, then once it has aborted, the combined signal in the next fetch is already aborted from the start.

For types, the DOM type definitions bundled with TypeScript (lib.dom.d.ts in typescript 7.0.2) include any(signals: AbortSignal[]) and timeout(milliseconds: number). The type check passed with an ordinary configuration that includes DOM in tsconfig's lib.

Wiring it into a button

Here is a component that uses the hook. The cancel button can only be pressed while a fetch is in progress.

tsx
function CatFetcher({ url }: { url: string }) {
  const { state, start, cancel } = useFetchWithCancel(3000);
  const loading = state.status === 'loading';
  const elapsed = useElapsed(loading);
  return (
    <section className="fetcher">
      <div className="buttons">
        <button onClick={() => start(url)}>取得する</button>
        <button onClick={cancel} disabled={!loading}>中止</button>
      </div>
      <p className="status" data-status={state.status}>{message(state)}</p>
      <p className="elapsed">経過 {(elapsed / 1000).toFixed(1)} 秒</p>
    </section>
  );
}

message() is a function that returns text such as "Fetch canceled" or "Stopped because it did not finish within 3 seconds" depending on state. useElapsed() is a hook that counts the time elapsed during a fetch every 0.1 seconds. In the verification code, I switch between two hooks with a URL parameter so I can compare them later, but I have left that out here.

Below is a run against an API that takes 5 seconds to respond. I pressed Fetch, then Cancel, then Fetch again. The first request was stopped by the cancel button, and the second was stopped by the 3-second timeout.

Screen recording: pressing the fetch button and then the cancel button about 1.6 seconds later shows the message "Fetch canceled". Pressing the fetch button again shows "Stopped because it did not finish within 3 seconds" at 3.0 seconds elapsed. The UI labels in the image are in Japanese.
Messages shown when stopped by the cancel button and when stopped by the 3-second timeout (API takes 5 seconds to respond; UI labels in Japanese)

Does the connection to the server get closed by a timeout or the cancel button?

I drove Chromium with Playwright and lined up what the screen shows against the times recorded by the server (in milliseconds since the request was received). First, an API that responds in 1 second. That is faster than the 3-second timeout, so the fetch succeeded.

text
--- 1. API that returns in 1 second (timeout is 3 seconds)
  押す前: まだ取得していません /中止ボタン disabled: true
  0.3秒後: 取得しています… /中止ボタン disabled: false
  1032ms 後: 取得しました:たま(3歳)
  サーバー:     0ms /api/cat?delay=1000 受信
  サーバー:  1002ms /api/cat?delay=1000 応答を送り終えた

With the API that takes 5 seconds, the request timed out at 3 seconds. When I pressed the cancel button 1 second in, it stopped at that point. In both cases, the server recorded that the connection was closed before the response finished. So the connection itself was cut, not just the result discarded in the browser.

text
--- 2. API that takes 5 seconds (timeout is 3 seconds)
  3038ms 後: 3秒たっても終わらないため、取得をやめました
  サーバー:     0ms /api/cat?delay=5000 受信
  サーバー:  3000ms /api/cat?delay=5000 送り終える前に接続が切れた
--- 3. API that takes 5 seconds; press the cancel button after 1 second
  1088ms 後: 取得を中止しました
  サーバー:     0ms /api/cat?delay=5000 受信
  サーバー:  1051ms /api/cat?delay=5000 送り終える前に接続が切れた
  さらに2.5秒後(時間切れの3秒を過ぎた): 取得を中止しました

The timer of the timeout signal keeps running even after the cancel button has stopped the request. The MDN page on AbortSignal.timeout() (English version) also says that the timeout timer is not canceled when another signal combined with AbortSignal.any() aborts. In my test environment, I combined a 0.5-second timeout signal with an AbortController signal, then called abort() 0.1 seconds later. Right after abort(), the timeout signal had not yet aborted. It had aborted 0.6 seconds later. Even so, the reason of the combined signal stayed as the first AbortError. In the component above, the message after the 3-second timeout passes is still "Fetch canceled".

A timeout while reading the body could not be told apart by err.name

The MDN example for AbortSignal.any() separates cancellation from timeout by checking the name of the error caught in catch, as AbortError or TimeoutError. For comparison, I also prepared a hook that uses this approach in the catch block.

ts

if (err instanceof DOMException && err.name === 'TimeoutError') {
        setState({ status: 'timeout' });
      } else if (err instanceof DOMException && err.name === 'AbortError') {
        setState({ status: 'canceled' });

I prepared an API that returns the headers and the first part of the body immediately, then sends the rest of the body after 5 seconds, and tested this approach against it. The request stopped at 3 seconds, but the message shown was "Fetch canceled".

text
--- 0b. API where the headers return immediately and the rest of the body takes 5 seconds
  3047ms 後: 取得を中止しました
  サーバー:     0ms /api/slow-body 受信
  サーバー:     0ms /api/slow-body ヘッダーと本文の最初を送った
  サーバー:  3000ms /api/slow-body 送り終える前に接続が切れた

fetch() itself resolves once the headers arrive. What stops is the res.text() call that follows. To reproduce the same situation in the browser with a 0.5-second timeout, I checked the error that res.text() throws when it fails.

text
--- 8. res.text() error when the body read stops partway through
{
  "any() でまとめたシグナル": {
    "rejectedAt": "res.text()",
    "name": "AbortError",
    "message": "The user aborted a request.",
    "sameAsSignalReason": false,
    "signalReasonName": "TimeoutError"
  },
  "AbortSignal.timeout() だけ": {
    "rejectedAt": "res.text()",
    "name": "AbortError",
    "message": "The user aborted a request.",
    "sameAsSignalReason": false,
    "signalReasonName": "TimeoutError"
  }
}

The signal's reason is TimeoutError, but the error from res.text() is a different AbortError. The result is the same when only AbortSignal.timeout() is passed, without AbortSignal.any(). In contrast, when the request stopped before the headers arrived, the error from fetch() was the same object as the signal's reason (TimeoutError).

The steps to abort a fetch() call in the Fetch spec say that stopping the body read also makes the signal's reason the error. The behavior of Chromium 153 in my environment differed from this.

Point

To find out why the request stopped, read the reason from the signal.reason of the signal you passed to fetch, not from the error caught in catch. Use err only when the signal has not aborted, such as for a network error or an error thrown when res.ok is false.

The first code block shows the hook with catch changed to read from signal.reason. With the same API, the timeout message was shown even when the request stopped during body reading: "Stopped because it did not finish within 3 seconds."

text
--- 4. API where the headers return immediately and the rest of the body takes 5 seconds
  3036ms 後: 3秒たっても終わらないため、取得をやめました
  サーバー:     0ms /api/slow-body 受信
  サーバー:     0ms /api/slow-body ヘッダーと本文の最初を送った
  サーバー:  2999ms /api/slow-body 送り終える前に接続が切れた

This result also shows that the timeout covers the whole process until the body is fully read, not just until fetch() resolves.

Pressing fetch again during a request, and unmounting the component

When I press Fetch again during a request, start() first calls abort() on the previous AbortController. In the previous request's catch, controllerRef.current has already been replaced by the new AbortController, so it returns without doing anything. I pressed the button again 0.5 seconds into an API that takes 1 second, and read the display every 50 milliseconds for 2.5 seconds. "Fetch canceled" never appeared. Only the previous request was cut, and the new request's result was shown.

text
--- 5. API that takes 1 second; press "fetch" again after 0.5 seconds
  2.5秒の間に出た表示: ["取得しています…","取得しました:たま(3歳)"]
  サーバー:     0ms /api/cat?delay=1000 受信
  サーバー:     0ms /api/cat?delay=1000 受信
  サーバー:   544ms /api/cat?delay=1000 送り終える前に接続が切れた
  サーバー:  1001ms /api/cat?delay=1000 応答を送り終えた

When the component is removed from the screen, I call abort() in the cleanup function of useEffect. I unchecked the Show checkbox during a fetch to unmount the component, and the connection to the server was closed at that point. Counting the browser console messages, excluding the React DevTools notice, there were 0 warnings or errors.

text
--- 6. Turn off "show" while fetching to unmount the component
  コンポーネントの数: 0
  サーバー:     0ms /api/cat?delay=5000 受信
  サーバー:  1044ms /api/cat?delay=5000 送り終える前に接続が切れた

Finally, according to the MDN English page on AbortSignal.timeout() mentioned above, the time for AbortSignal.timeout() is counted only while the page is actually running, so it pauses while the page is in the bfcache, for example. The timeout timer also cannot be canceled once started. If you need to stop the timer reliably, the page suggests combining an AbortController with setTimeout() and clearTimeout().

​Posted by 86