Skip to main content

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.

intermediateuseFetchretriesmockingerrors
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>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/retries hyper-fetch-react-retries && cd hyper-fetch-react-retries && npm install && npm run dev
What it shows
  1. retry sets how many times a failed request is sent again.
  2. retryTime sets the wait in milliseconds before each retry.
  3. Final result callbacks: onSuccess and onError fire once, after the last attempt.
  4. Per-attempt events: onRequestStart and the client's request events report every attempt.
  5. Mocking makes the failures repeatable: the first attempts answer 503 on purpose.

How it works​

  1. getQuoteRequest is created with the retry options:

    export const getQuoteRequest = client.createRequest<{ response: Quote }>()({
    endpoint: "/quotes/random",
    retry: 3,
    retryTime: 1000,
    });

    setRetry() and setRetryTime() change them on a single request. setRetryOnError((response) => boolean) decides per response whether a retry makes sense, for example only for 5xx statuses.

  2. dummyjson does not fail on demand, so api.ts attaches a mock with setMock(). It answers 503 while failuresLeft is above zero, then returns a quote. Retries are run by the dispatcher, so a real failing server is retried the same way.

  3. App counts attempts with onRequestStart, which fires for the first attempt and for every retry.

  4. Between attempts the hook already holds the failed response, and loading is false while the retry timer runs. onError fires only when no retry is left, so the app shows "retrying" until then and the final error after it.

  5. AttemptLog subscribes to client.requestManager.events. Each response carries details.retries and details.willRetry, which tell whether another attempt is coming.

Retries also apply to useSubmit and send(). Only retry mutations that are safe to repeat.

When to use it
  • 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.

Summary

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.