Retries
A quote that loads from an unreliable server. Pick how many attempts fail before one succeeds and press Fetch quote. The request is retried up to three times, one second apart, and the log lists every attempt. With four failures, the retries run out and the final error is shown.
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";
type Entry = {
id: number;
text: string;
kind: "start" | "retry" | "error" | "success";
};
let nextId = 0;
/** Reads the client's request events. Every retry is a new attempt with its own start and response. */
export const AttemptLog = () => {
const [entries, setEntries] = useState<Entry[]>([]);
useEffect(() => {
const { events } = client.requestManager;
const add = (kind: Entry["kind"], text: string) => {
// Take the id now - the updater may run later, after other events changed the counter
nextId += 1;
const id = nextId;
setEntries((list) => [{ id, kind, text }, ...list].slice(0, 10));
};
const time = () => new Date().toLocaleTimeString();
const unmountStart = events.onRequestStart(() => add("start", `${time()} attempt started`));
const unmountResponse = events.onResponse(({ response, details }) => {
if (response.success) {
add("success", `${time()} ${response.status} after ${details.retries} retries`);
} else if (details.willRetry) {
add("retry", `${time()} ${response.status}, retry ${details.retries + 1} in 1 s`);
} else {
add("error", `${time()} ${response.status}, giving up after ${details.retries} retries`);
}
});
return () => {
unmountStart();
unmountResponse();
};
}, []);
return (
<article>
<header>
<strong>Attempts</strong>
</header>
<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/retries hyper-fetch-react-retries && cd hyper-fetch-react-retries && npm install && npm run devretrysets how many times a failed request is sent again.retryTimesets the wait in milliseconds before each retry.- Final result callbacks:
onSuccessandonErrorfire once, after the last attempt. - Per-attempt events:
onRequestStartand the client's request events report every attempt. - Mocking makes the failures repeatable: the first attempts answer
503on purpose.
How it works
-
getQuoteRequestis created with the retry options:export const getQuoteRequest = client.createRequest<{ response: Quote }>()({endpoint: "/quotes/random",retry: 3,retryTime: 1000,});setRetry()andsetRetryTime()change them on a single request.setRetryOnError((response) => boolean)decides per response whether a retry makes sense, for example only for5xxstatuses. -
dummyjson does not fail on demand, so
api.tsattaches a mock withsetMock(). It answers503whilefailuresLeftis above zero, then returns a quote. Retries are run by the dispatcher, so a real failing server is retried the same way. -
Appcounts attempts withonRequestStart, which fires for the first attempt and for every retry. -
Between attempts the hook already holds the failed response, and
loadingisfalsewhile the retry timer runs.onErrorfires only when no retry is left, so the app shows "retrying" until then and the final error after it. -
AttemptLogsubscribes toclient.requestManager.events. Each response carriesdetails.retriesanddetails.willRetry, which tell whether another attempt is coming.
Retries also apply to useSubmit and send(). Only retry mutations that are safe to repeat.
- Requests that can fail for a moment: flaky networks, rate limits, servers that restart.
- Background data such as dashboards, where a short delay is better than an error.
Related
retry and retryTime make HyperFetch send a failed request again after a pause. Per-attempt events show each try, and
the final onSuccess or onError tells you how it ended.
