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.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
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>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/timeouts hyper-fetch-react-timeouts && cd hyper-fetch-react-timeouts && npm install && npm run devsetAdapterDefaultssets one timeout for every request of the client.options: { timeout }andsetOptionsset it for one request.TimeoutErrortells a timeout apart from other failures withinstanceof.refetch()retries after a timeout.
How it works
-
The fetch adapter aborts every request after 5 seconds by default.
api.tschanges that for the whole client withclient.adapter.setAdapterDefaults(() => ({ timeout: 4000 })). -
getProductsets its own limit inoptions, which holds the adapter options of a request:options: { timeout: 2000 }, -
App.tsxbuilds the request from the chosen values withsetQueryParams({ delay })andsetOptions({ timeout }). DummyJSON'sdelayquery param makes the server answer slowly. -
When the time runs out, the adapter aborts the call and the response has status
0and aTimeoutErroraserror.send()and the hooks resolve with it, they don't throw.error instanceof TimeoutErrorpicks the message. -
Retry calls
refetch(). Allow 5 s and retry raises the limit. The timeout is not part of the cache key, souseFetchlists it independenciesand sends the request again when it changes. -
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.
- 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.
Related
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.
