Guides
Retries and errors
Retry failed requests with retry(), set attempts per query or per client, choose delays and which errors to retry, time requests out, and show errors.
retry() is a plugin that retries a client's failed requests. With its defaults, a request that fails in the browser is retried 3 times, waiting 1, 2 and then 4 seconds, before the query counts as failed. Readers keep suspending, or keep showing their current data, the whole time.
Nothing retries unless the client has it, on its own or through recommended():
const const queryClient: QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
};
}>
queryClient = createQueryClient<readonly [Plugin<Retry>]>(config?: Omit<QueryClientConfig, "defaults" | "plugins"> & {
readonly defaults?: NoInfer<Omit<CoreOptions, "ssr"> & Partial<{
readonly retry: number | false | undefined;
}>> | undefined;
readonly plugins?: readonly [Plugin<Retry>] | undefined;
}): QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
};
}>
Create a query client. Behaviors are opt-in: pass plugins, such as
recommended(). The client's root is what they declare.
createQueryClient({ plugins?: readonly [Plugin<Retry>] | undefinedplugins: [function retry(options?: RetryOptions): Plugin<Retry>Retry failed requests. Thrown Responses (router redirects and
not-founds) and cancelled requests aren't retried,
server clients never retry, and a browser that is offline
waits until it's back online before retrying. A query sets its own
attempts with retry.
retry()] });
// or
const const withEverything: QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>
withEverything = createQueryClient<Recommended>(config?: Omit<QueryClientConfig, "defaults" | "plugins"> & {
readonly defaults?: NoInfer<Omit<CoreOptions, "ssr"> & Partial<{
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | false | undefined;
}>> | undefined;
readonly plugins?: Recommended | undefined;
}): QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | ... 1 more ... | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | ... 1 more ... | undefined) => number | ... 1 more ... | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | false | undefined;
};
}>
Create a query client. Behaviors are opt-in: pass plugins, such as
recommended(). The client's root is what they declare.
createQueryClient({ plugins?: Recommended | undefinedplugins: function recommended(): RecommendedThe behaviors most apps want: retries, refetching on focus and reconnect,
and polling. Pass it as the client's plugins, or spread it among your own:
recommended() });
Some requests are never retried:
- Cancelled requests, whose
signalwas aborted. - Requests on a server client. The user is waiting for the HTML, and the browser can try again.
Attempts per query
A query sets its own attempts with retry: a number of retries after the first attempt, or false for none. It wins over the plugin's attempts:
import { const queryOptions: QueryOptionsBuilder<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>
queryOptions } from "~/raf.ts";
export function function postQuery(input: {
slug: string;
}): QueryOptions<readonly ["posts", "bySlug", string], Post, Post, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>
postQuery(input: {
slug: string;
}
input: { slug: stringslug: string }) {
return queryOptions<readonly ["posts", "bySlug", string], Post, Post>(options: BaseOptions<readonly ["posts", "bySlug", string]> & Partial<{
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | false | undefined;
}> & {
readonly queryFn: (context: QueryFunctionContext<readonly ["posts", "bySlug", string], {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | ... 1 more ... | undefined) => number | ... 1 more ... | undefined;
};
readonly context: {};
readonly options: {
...;
};
}>) => Awaitable<...>;
readonly select?: ((data: Post) => Post) | undefined;
}): QueryOptions<...> (+1 overload)
queryOptions({
BaseOptions<readonly ["posts", "bySlug", string]>.queryKey: readonly ["posts", "bySlug", string]A plain array, usually built by a group(). Handles keep its literal type.
queryKey: posts<readonly ["bySlug", string]>(rest_0: "bySlug", rest_1: string): readonly ["posts", "bySlug", string]posts("bySlug", input: {
slug: string;
}
input.slug: stringslug),
queryFn: (context: QueryFunctionContext<readonly ["posts", "bySlug", string], {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>) => Awaitable<...>
queryFn: () => function getPost(slug: string): Promise<Post>getPost(input: {
slug: string;
}
input.slug: stringslug),
retry?: number | false | undefinedretry: 5, // or `false`
});
}
retry() declares the option, so a factory can set it when its queryOptions, the one the app's raf.ts binds to its client, is bound to a client that has retry(). On any other builder, retry is a type error.
The client's defaults set it for every query that doesn't set its own:
const const once: QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>
once = createQueryClient<Recommended>(config?: Omit<QueryClientConfig, "defaults" | "plugins"> & {
readonly defaults?: NoInfer<Omit<CoreOptions, "ssr"> & Partial<{
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | false | undefined;
}>> | undefined;
readonly plugins?: Recommended | undefined;
}): QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | ... 1 more ... | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | ... 1 more ... | undefined) => number | ... 1 more ... | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | false | undefined;
};
}>
Create a query client. Behaviors are opt-in: pass plugins, such as
recommended(). The client's root is what they declare.
createQueryClient({
plugins?: Recommended | undefinedplugins: function recommended(): RecommendedThe behaviors most apps want: retries, refetching on focus and reconnect,
and polling. Pass it as the client's plugins, or spread it among your own:
recommended(),
defaults?: NoInfer<Omit<CoreOptions, "ssr"> & Partial<{
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | false | undefined;
}>> | undefined
defaults: { retry?: number | false | undefinedretry: 1 },
});
Options
retry({ attempts, delay, when }) configures the plugin:
| Option | Default |
|---|---|
attempts | 3: retries after the first attempt, for queries with no retry of their own and no default for it |
delay | Doubling from 1 second, at most 30 seconds |
when | Every error but a thrown Response: whether an error is worth retrying |
delay(attempt) gets the retry's index, from 0. when(error) is the place to skip errors that won't go away:
const const patient: QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
};
}>
patient = createQueryClient<readonly [Plugin<Retry>]>(config?: Omit<QueryClientConfig, "defaults" | "plugins"> & {
readonly defaults?: NoInfer<Omit<CoreOptions, "ssr"> & Partial<{
readonly retry: number | false | undefined;
}>> | undefined;
readonly plugins?: readonly [Plugin<Retry>] | undefined;
}): QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
};
}>
Create a query client. Behaviors are opt-in: pass plugins, such as
recommended(). The client's root is what they declare.
createQueryClient({
plugins?: readonly [Plugin<Retry>] | undefinedplugins: [
function retry(options?: RetryOptions): Plugin<Retry>Retry failed requests. Thrown Responses (router redirects and
not-founds) and cancelled requests aren't retried,
server clients never retry, and a browser that is offline
waits until it's back online before retrying. A query sets its own
attempts with retry.
retry({
RetryOptions.attempts?: number | undefinedRetries after the first attempt. A query's retry, or the client's default for it, wins. Default 3.
attempts: 5,
RetryOptions.delay?: ((attempt: number) => number) | undefinedWait before retry n (0-based), in ms. Default: doubling from 1 s, at most 30 s.
delay: (attempt: numberattempt) => 500 * (attempt: numberattempt + 1),
RetryOptions.when?: ((error: unknown) => boolean) | undefinedWhether an error is worth retrying. Default: every error but a thrown Response.
when: (error: unknownerror) => !(error: unknownerror instanceof class HttpErrorHttpError && error: HttpErrorerror.HttpError.status: numberstatus === 404),
}),
],
});
Retries while offline
In the browser, a retry waits while navigator.onLine is false: after the delay, it waits for the window's online event. The query counts as fetching meanwhile. The first attempt always runs.
Timeouts
timeout(ms) is another plugin: it fails a request that takes longer than ms with a QueryTimeoutError, and aborts its signal. Both wrap each request with a link, and links wrap each other in the order of plugins, outermost first, so where it goes decides what it times:
// Each attempt gets 10 seconds.
const const perAttempt: QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
};
}>
perAttempt = createQueryClient<readonly [Plugin<Retry>, Plugin<NoDecl>]>(config?: Omit<QueryClientConfig, "defaults" | "plugins"> & {
readonly defaults?: NoInfer<Omit<CoreOptions, "ssr"> & Partial<{
readonly retry: number | false | undefined;
}>> | undefined;
readonly plugins?: readonly [Plugin<Retry>, Plugin<NoDecl>] | undefined;
}): QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
};
}>
Create a query client. Behaviors are opt-in: pass plugins, such as
recommended(). The client's root is what they declare.
createQueryClient({ plugins?: readonly [Plugin<Retry>, Plugin<NoDecl>] | undefinedplugins: [function retry(options?: RetryOptions): Plugin<Retry>Retry failed requests. Thrown Responses (router redirects and
not-founds) and cancelled requests aren't retried,
server clients never retry, and a browser that is offline
waits until it's back online before retrying. A query sets its own
attempts with retry.
retry(), function timeout(ms: number): PluginFail a request (and abort its signal) when it takes longer than ms.
timeout(10_000)] });
// The request and all its retries get 30 seconds.
const const overall: QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
};
}>
overall = createQueryClient<readonly [Plugin<NoDecl>, Plugin<Retry>]>(config?: Omit<QueryClientConfig, "defaults" | "plugins"> & {
readonly defaults?: NoInfer<Omit<CoreOptions, "ssr"> & Partial<{
readonly retry: number | false | undefined;
}>> | undefined;
readonly plugins?: readonly [Plugin<NoDecl>, Plugin<Retry>] | undefined;
}): QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
};
}>
Create a query client. Behaviors are opt-in: pass plugins, such as
recommended(). The client's root is what they declare.
createQueryClient({ plugins?: readonly [Plugin<NoDecl>, Plugin<Retry>] | undefinedplugins: [function timeout(ms: number): PluginFail a request (and abort its signal) when it takes longer than ms.
timeout(30_000), function retry(options?: RetryOptions): Plugin<Retry>Retry failed requests. Thrown Responses (router redirects and
not-founds) and cancelled requests aren't retried,
server clients never retry, and a browser that is offline
waits until it's back online before retrying. A query sets its own
attempts with retry.
retry()] });
Showing errors
What the user sees depends on whether there was data before the failure.
The first load fails. Reading the query throws to the nearest error boundary. Before the boundary renders its children again, start the query again the way the loader did, so the reader suspends on the new request instead of throwing the old error:
function function CommentsSection(): React.JSX.ElementCommentsSection() {
return (
<class CatchBoundaryCatchBoundary
getResetKey: () => unknowngetResetKey={() => const loaderData: {
comments: QueryHandle<typeof commentsQuery>;
}
loaderData.comments: QueryHandle<(input: {
slug: string;
}) => InfiniteQueryOptions<readonly ["posts", "comments", string], CommentPage, number, InfiniteData<CommentPage, number>, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
...;
};
}>>
comments.QueryHandle<(input: { slug: string; }) => InfiniteQueryOptions<readonly ["posts", "comments", string], CommentPage, number, InfiniteData<CommentPage, number>, { ...; }>>.input: {
slug: string;
}
input.slug: stringslug}
errorComponent?: ErrorRouteComponent | undefinederrorComponent={function CommentsError(props: ErrorComponentProps): React.JSX.ElementCommentsError}
>
<const Suspense: React.ExoticComponent<React.SuspenseProps>Lets you display a fallback until its children have finished loading.
Suspense React.SuspenseProps.fallback?: ReactNodeA fallback react tree to show when a Suspense child (like React.lazy) suspends
fallback={<function CommentsSkeleton(): ReactNodeCommentsSkeleton />}>
<function Comments(props: {
readonly handle: QueryHandle<typeof commentsQuery>;
}): ReactNode
Comments handle: QueryHandle<(input: {
slug: string;
}) => InfiniteQueryOptions<readonly ["posts", "comments", string], CommentPage, number, InfiniteData<CommentPage, number>, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
...;
};
}>>
handle={const loaderData: {
comments: QueryHandle<typeof commentsQuery>;
}
loaderData.comments: QueryHandle<(input: {
slug: string;
}) => InfiniteQueryOptions<readonly ["posts", "comments", string], CommentPage, number, InfiniteData<CommentPage, number>, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
...;
};
}>>
comments} />
</const Suspense: React.ExoticComponent<React.SuspenseProps>Lets you display a fallback until its children have finished loading.
Suspense>
</class CatchBoundaryCatchBoundary>
);
}
function function CommentsError(props: ErrorComponentProps): React.JSX.ElementCommentsError(props: ErrorComponentPropsprops: type ErrorComponentProps<TError = unknown> = {
error: TError;
info?: {
componentStack: string;
};
reset: () => void;
}
ErrorComponentProps) {
const const queryClient: QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>
queryClient = function useQueryClient(): QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>
useQueryClient();
return (
<React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div React.HTMLAttributes<HTMLDivElement>.role?: React.AriaRole | undefinedrole="alert">
<React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>
Couldn't load comments:{" "}
{props: ErrorComponentPropsprops.error: unknownerror instanceof var Error: ErrorConstructorError
? props: ErrorComponentPropsprops.error: Errorerror.Error.message: stringmessage
: var String: StringConstructor
(value?: any) => string
Allows manipulation and formatting of text strings and determination and location of substrings within strings.
String(props: ErrorComponentPropsprops.error: unknownerror)}
</React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>
<React.JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>button
React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | undefinedonClick={() => {
void load<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}, {
...;
}>(client: QueryClient<...>, entries: {
...;
} & {
...;
}): Promise<...>
Start a loader's queries and return a serializable handle for each. It
starts every entry before it waits for any, so the order of the entries
can't create a waterfall. Resolves with [handles, data] once every
swr and revalidate entry has data, and rejects with the error as soon
as one fails.
prefetch entries never make it reject. A skipToken in place of an
entry starts nothing and gets no handle.
load(const queryClient: QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>
queryClient, {
comments: LoadEntry<(input: {
slug: string;
}) => InfiniteQueryOptions<readonly ["posts", "comments", string], CommentPage, number, InfiniteData<CommentPage, number>, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
...;
};
}>, "prefetch">
comments: prefetch<(input: {
slug: string;
}) => InfiniteQueryOptions<readonly ["posts", "comments", string], CommentPage, number, InfiniteData<CommentPage, number>, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
...;
};
}>>(factory: (input: {
slug: string;
}) => InfiniteQueryOptions<readonly ["posts", "comments", string], CommentPage, number, InfiniteData<CommentPage, number>, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
...;
};
}>, ...args: LoadEntryArgs<...>): LoadEntry<...>
Start the query if the cache has no fresh data, and don't wait for it.
It never makes the load reject: errors show up where a component reads
the handle.
prefetch(function commentsQuery(input: {
slug: string;
}): InfiniteQueryOptions<readonly ["posts", "comments", string], CommentPage, number, InfiniteData<CommentPage, number>, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
...;
};
}>
commentsQuery, const loaderData: {
comments: QueryHandle<typeof commentsQuery>;
}
loaderData.comments: QueryHandle<(input: {
slug: string;
}) => InfiniteQueryOptions<readonly ["posts", "comments", string], CommentPage, number, InfiniteData<CommentPage, number>, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
...;
};
}>>
comments.QueryHandle<(input: { slug: string; }) => InfiniteQueryOptions<readonly ["posts", "comments", string], CommentPage, number, InfiniteData<CommentPage, number>, { ...; }>>.input: {
slug: string;
}
input),
});
props: ErrorComponentPropsprops.reset: () => voidreset();
}}
>
Try again
</React.JSX.IntrinsicElements.button: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>button>
</React.JSX.IntrinsicElements.div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>div>
);
}Any error boundary works: CatchBoundary from TanStack Router, react-error-boundary, Next.js's error.tsx, or your own class component.
A background refetch fails. The existing data stays on screen: losing it because a refetch failed would be worse than showing it a little longer. The error is on the reader's state as error, for a hint:
const [const postThenable: QueryValue<(input: {
slug: string;
}) => QueryOptions<readonly ["posts", "bySlug", string], Post, Post, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>>
postThenable, const controls: QueryState<(input: {
slug: string;
}) => QueryOptions<readonly ["posts", "bySlug", string], Post, Post, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>>
controls] = useQuery<(input: {
slug: string;
}) => QueryOptions<readonly ["posts", "bySlug", string], Post, Post, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>>(factory: (input: {
slug: string;
}) => QueryOptions<readonly ["posts", "bySlug", string], Post, Post, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>, handle: QueryHandle<...>, options?: UseQueryOptions): readonly [...]
Read a query by its handle.
useQuery(function postQuery(input: {
slug: string;
}): QueryOptions<readonly ["posts", "bySlug", string], Post, Post, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>
postQuery, const loaderData: {
post: QueryHandle<typeof postQuery>;
}
loaderData.post: QueryHandle<(input: {
slug: string;
}) => QueryOptions<readonly ["posts", "bySlug", string], Post, Post, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>>
post);
const const post: Postpost = use<Post>(usable: React.Usable<Post>): Postuse(const postThenable: QueryValue<(input: {
slug: string;
}) => QueryOptions<readonly ["posts", "bySlug", string], Post, Post, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>>
postThenable);
{
const controls: QueryState<(input: {
slug: string;
}) => QueryOptions<readonly ["posts", "bySlug", string], Post, Post, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>>
controls.QueryState<(input: { slug: string; }) => QueryOptions<readonly ["posts", "bySlug", string], Post, Post, { readonly "~options": { readonly retry: (value: number | false | undefined) => number | false | undefined; readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined; readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined; readonly refetchInterval: (value: number | ... 1 more ... | undefined) => number | ... 1 more ... | undefined; }; readonly context: {}; readonly options: { ...; }; }>>.error: unknownThe last request's error while it's the latest outcome.
error ? (
<React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p React.HTMLAttributes<HTMLParagraphElement>.role?: React.AriaRole | undefinedrole="status">
Couldn't refresh. Showing data from {function formatTime(value: number): stringformatTime(const controls: QueryState<(input: {
slug: string;
}) => QueryOptions<readonly ["posts", "bySlug", string], Post, Post, {
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined;
readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined;
readonly refetchInterval: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
readonly refetchOnWindowFocus: boolean | undefined;
readonly refetchOnReconnect: boolean | undefined;
readonly refetchInterval: number | ... 1 more ... | undefined;
};
}>>
controls.QueryState<(input: { slug: string; }) => QueryOptions<readonly ["posts", "bySlug", string], Post, Post, { readonly "~options": { readonly retry: (value: number | false | undefined) => number | false | undefined; readonly refetchOnWindowFocus: (value: boolean | undefined) => boolean | undefined; readonly refetchOnReconnect: (value: boolean | undefined) => boolean | undefined; readonly refetchInterval: (value: number | ... 1 more ... | undefined) => number | ... 1 more ... | undefined; }; readonly context: {}; readonly options: { ...; }; }>>.updatedAt: numberWhen the data was fetched (ms since epoch); 0 without data.
updatedAt)}.
</React.JSX.IntrinsicElements.p: React.DetailedHTMLProps<React.HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>p>
) : null;
}Make the next request fail in the demo, then reload a post to see each case:
Errors from loaders
A failed prefetch never makes load reject: the error surfaces where the data is read, and only that part of the page shows it. A failed swr or revalidate makes load reject, so it reaches the route's error boundary (errorComponent in TanStack Router, error.tsx in Next.js), replacing the page.
This is one more reason to choose per query: wait with swr for what the page can't do without, and prefetch the rest, so a failing sidebar doesn't take the whole page down.
One place for every error
A plugin's link sees every request of the client, so it's the place for logging and toasts. Put it before retry() to see each request's final error, after its retries. It can declare an option of its own, for a per-query message:
interface ErrorReports {
readonly ErrorReports.options: {
readonly errorMessage?: string;
}
options: { readonly errorMessage?: string | undefinederrorMessage?: string };
}
const const reportErrors: Plugin<NoInfer<ErrorReports>>reportErrors = plugin<ErrorReports>(definition?: PlainDefinition<NoInfer<ErrorReports>> | undefined): Plugin<NoInfer<ErrorReports>> (+2 overloads)A plugin for a client, with what it declares: the per-query options it
reads and the context it gives every queryFn. A client's queries take
those options, and get that context, only when the client has the plugin.
plugin<ErrorReports>({
PlainDefinition<NoInfer<ErrorReports>>.link?: LinkOf<NoInfer<ErrorReports>, Operation<NoInfer<ErrorReports>>> | undefinedWraps every request, like a tRPC link. Call next(op) to run the
rest of the chain; the last link is the query's own queryFn.
link: async (op: Operation<NoInfer<ErrorReports>>op, next: (op: Operation<NoInfer<ErrorReports>>) => Promise<unknown>next) => {
try {
return await next: (op: Operation<NoInfer<ErrorReports>>) => Promise<unknown>next(op: Operation<NoInfer<ErrorReports>>op);
} catch (function (local var) error: unknownerror) {
if (!op: Operation<NoInfer<ErrorReports>>op.Operation<NoInfer<ErrorReports>>.signal: AbortSignalsignal.AbortSignal.aborted: booleanThe aborted read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (true) or not (false).
aborted) {
function reportError(error: unknown, context: {
readonly queryKey: unknown;
}): void
reportError(function (local var) error: unknownerror, { queryKey: unknownqueryKey: op: Operation<NoInfer<ErrorReports>>op.Operation<NoInfer<ErrorReports>>.queryKey: QueryKeyqueryKey });
function showToast(message: string): voidshowToast(op: Operation<NoInfer<ErrorReports>>op.Operation<NoInfer<ErrorReports>>.options: Partial<{
readonly errorMessage?: string;
}> & QueryOptions<QueryKey, unknown, unknown, RootTypes>
The query's options, over the client's defaults.
options.errorMessage?: string | undefinederrorMessage ?? "Something went wrong");
}
throw function (local var) error: unknownerror;
}
},
});
const const reporting: QueryClient<{
readonly "~options": {
readonly errorMessage: (value: string | undefined) => string | undefined;
readonly retry: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly errorMessage: string | undefined;
readonly retry: number | false | undefined;
};
}>
reporting = createQueryClient<readonly [Plugin<NoInfer<ErrorReports>>, Plugin<Retry>]>(config?: Omit<QueryClientConfig, "defaults" | "plugins"> & {
readonly defaults?: NoInfer<Omit<CoreOptions, "ssr"> & Partial<{
readonly errorMessage: string | undefined;
readonly retry: number | false | undefined;
}>> | undefined;
readonly plugins?: readonly [Plugin<NoInfer<ErrorReports>>, Plugin<Retry>] | undefined;
}): QueryClient<{
readonly "~options": {
...;
};
readonly context: {};
readonly options: {
readonly errorMessage: string | undefined;
readonly retry: number | false | undefined;
};
}>
Create a query client. Behaviors are opt-in: pass plugins, such as
recommended(). The client's root is what they declare.
createQueryClient({ plugins?: readonly [Plugin<NoInfer<ErrorReports>>, Plugin<Retry>] | undefinedplugins: [const reportErrors: Plugin<NoInfer<ErrorReports>>reportErrors, function retry(options?: RetryOptions): Plugin<Retry>Retry failed requests. Thrown Responses (router redirects and
not-founds) and cancelled requests aren't retried,
server clients never retry, and a browser that is offline
waits until it's back online before retrying. A query sets its own
attempts with retry.
retry()] });
Redirects
In TanStack Start, a queryFn can throw the router's redirect(), for instance when a session has expired. setupRouterIntegration turns it into a navigation wherever the query failed: a loader, a render or a background refetch.
A redirect is a thrown Response, which retry() doesn't retry, so it navigates at once. A when of your own replaces that check, so keep it:
const const withRedirects: QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
};
}>
withRedirects = createQueryClient<readonly [Plugin<Retry>]>(config?: Omit<QueryClientConfig, "defaults" | "plugins"> & {
readonly defaults?: NoInfer<Omit<CoreOptions, "ssr"> & Partial<{
readonly retry: number | false | undefined;
}>> | undefined;
readonly plugins?: readonly [Plugin<Retry>] | undefined;
}): QueryClient<{
readonly "~options": {
readonly retry: (value: number | false | undefined) => number | false | undefined;
};
readonly context: {};
readonly options: {
readonly retry: number | false | undefined;
};
}>
Create a query client. Behaviors are opt-in: pass plugins, such as
recommended(). The client's root is what they declare.
createQueryClient({
plugins?: readonly [Plugin<Retry>] | undefinedplugins: [
function retry(options?: RetryOptions): Plugin<Retry>Retry failed requests. Thrown Responses (router redirects and
not-founds) and cancelled requests aren't retried,
server clients never retry, and a browser that is offline
waits until it's back online before retrying. A query sets its own
attempts with retry.
retry({
RetryOptions.when?: ((error: unknown) => boolean) | undefinedWhether an error is worth retrying. Default: every error but a thrown Response.
when: (error: unknownerror) =>
!function isRedirect(obj: any): obj is AnyRedirectCheck whether a value is a TanStack Router redirect Response.
isRedirect(error: unknownerror) &&
!(error: unknownerror instanceof class HttpErrorHttpError && error: HttpErrorerror.HttpError.status: numberstatus === 404),
}),
],
});