Skip to main content

Timeouts

A product card behind a slow server. Pick how long the server takes and how long the request may wait. When the server is slower than the timeout, the request is aborted and the card offers to retry, or to retry with a longer limit.

beginneruseFetcherrorscancellation
import { TimeoutError } from "@hyper-fetch/core";
import { useFetch } from "@hyper-fetch/react";
import { useEffect, useState } from "react";

import { getProduct } from "./api";

const DELAYS = [500, 1500, 3000];
const TIMEOUTS = [1000, 2000, 5000];

/** Elapsed time of the current attempt, for the progress bar. */
const useElapsed = (running: boolean) => {
const [elapsed, setElapsed] = useState(0);
useEffect(() => {
if (!running) return;
const startedAt = performance.now();
setElapsed(0);
const interval = setInterval(() => setElapsed(performance.now() - startedAt), 50);
return () => clearInterval(interval);
}, [running]);
return elapsed;
};

const Choice = ({
label,
values,
value,
onChange,
}: {
label: string;
values: number[];
value: number;
onChange: (value: number) => void;
}) => (
<fieldset>
<legend>{label}</legend>
<div role="group">
{values.map((option) => (
<button
key={option}
type="button"
className={option === value ? undefined : "outline secondary"}
onClick={() => onChange(option)}
>
{option / 1000} s
</button>
))}
</div>
</fieldset>
);

export const App = () => {
const [delay, setDelay] = useState(1500);
const [timeout, setTimeoutMs] = useState(2000);

// `setOptions` replaces the adapter options of this request instance. `delay` and `select` are dummyjson query
// params: answer after `delay` ms, return only these fields.
const request = getProduct.setQueryParams({ delay, select: "title,price,thumbnail" }).setOptions({ timeout });
// The timeout is not part of the cache key, so it is listed as a dependency to send the request again on change.
const { data, error, loading, refetch } = useFetch(request, { dependencies: [timeout] });
const elapsed = useElapsed(loading);

const timedOut = error instanceof TimeoutError;

return (
<main className="container">
<hgroup>
<h1>Timeouts</h1>
<p>Make the server slower than the timeout and the request is aborted with a TimeoutError you can retry.</p>
</hgroup>
<div className="grid-2">
<Choice label="Server answers after" values={DELAYS} value={delay} onChange={setDelay} />
<Choice label="Timeout" values={TIMEOUTS} value={timeout} onChange={setTimeoutMs} />
</div>
<article>
{loading && (
<>
<p aria-busy="true">
Waiting {(elapsed / 1000).toFixed(1)} s of {timeout / 1000} s
</p>
<progress value={Math.min(elapsed, timeout)} max={timeout} />
</>
)}
{!loading && timedOut && (
<>
<p className="error">
<strong>Timed out.</strong> The server did not answer within {timeout / 1000} s, so the request was
aborted.
</p>
<div role="group">
<button type="button" onClick={() => refetch()}>
Retry
</button>
<button type="button" className="secondary" onClick={() => setTimeoutMs(5000)}>
Allow 5 s and retry
</button>
</div>
</>
)}
{!loading && error && !timedOut && <p className="error">Request failed: {error.message}</p>}
{!loading && !error && data && (
<div className="product">
<img src={data.thumbnail} alt="" width={64} height={64} />
<div>
<strong>{data.title}</strong>
<p>${data.price}</p>
</div>
<button type="button" className="outline" onClick={() => refetch()}>
Send again
</button>
</div>
)}
</article>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/timeouts hyper-fetch-react-timeouts && cd hyper-fetch-react-timeouts && npm install && npm run dev
What it shows
  1. setAdapterDefaults sets one timeout for every request of the client.
  2. options: { timeout } and setOptions set it for one request.
  3. TimeoutError tells a timeout apart from other failures with instanceof.
  4. refetch() retries after a timeout.

How it works​

  1. The fetch adapter aborts every request after 5 seconds by default. api.ts changes that for the whole client with client.adapter.setAdapterDefaults(() => ({ timeout: 4000 })).

  2. getProduct sets its own limit in options, which holds the adapter options of a request:

    options: { timeout: 2000 },
  3. App.tsx builds the request from the chosen values with setQueryParams({ delay }) and setOptions({ timeout }). DummyJSON's delay query param makes the server answer slowly.

  4. When the time runs out, the adapter aborts the call and the response has status 0 and a TimeoutError as error. send() and the hooks resolve with it, they don't throw. error instanceof TimeoutError picks the message.

  5. Retry calls refetch(). Allow 5 s and retry raises the limit. The timeout is not part of the cache key, so useFetch lists it in dependencies and sends the request again when it changes.

  6. While the request runs, a progress bar compares the elapsed time with the limit.

Requests with retry set are retried after a timeout too, since it is a failed response like any other.

When to use it
  • Slow or unreliable APIs where a stuck request is worse than a quick error.
  • Search and autocomplete, where an old answer is not worth waiting for.
  • Long reports or exports, which need a longer limit than the client default.

Summary

setAdapterDefaults sets the client timeout and options.timeout or setOptions() overrides it per request. A timeout resolves the request with a TimeoutError, which the UI can show and retry.