Skip to content
rest-rpc
Esc
↑↓navigate↵open⌘Jpreview
On this page

TanStack Query

Typed query and mutation options for TanStack Query.

npm install @rest-rpc/tanstack-query
pnpm add @rest-rpc/tanstack-query
yarn add @rest-rpc/tanstack-query
bun add @rest-rpc/tanstack-query
nub add @rest-rpc/tanstack-query
aube add @rest-rpc/tanstack-query

createTanstackQueryUtils() takes a client and returns utils of the same shape, which create TanStack Query options and keys:

import { createClient } from "@rest-rpc/core";
import { createTanstackQueryUtils } from "@rest-rpc/tanstack-query";
import { getContract } from "./contract.ts" with { type: "macro" };

export const client = createClient(getContract());
export const queryUtils = createTanstackQueryUtils(client);

Queries and Mutations

const post = useQuery(
	queryUtils.posts.get.queryOptions({
		request: { params: { id: "post_1" } },
		select: (response) => response.body,
	}),
);

const create = useMutation(
	queryUtils.posts.create.mutationOptions({
		onSuccess: () =>
			queryClient.invalidateQueries({ queryKey: queryUtils.posts.list.key() }),
	}),
);

create.mutate({ body: { title: "Hello", body: "First post" } });
  • The query’s data is the whole response, so select reads its body.
  • Options take any TanStack Query option, plus fetchOptions for the client’s per-call options. TanStack Query passes the signal itself.
  • Pass skipToken as request to disable a query, typed.
  • error is typed like safe()’s, so narrow it with isDefinedError().

Infinite Queries

request maps each page param to the request for that page:

const posts = useInfiniteQuery(
	queryUtils.posts.feed.infiniteQueryOptions({
		request: (cursor: string | undefined) => ({
			query: { cursor, limit: 50 },
		}),
		initialPageParam: undefined,
		getNextPageParam: (lastPage) => lastPage.body.nextCursor,
	}),
);

Streamed Queries

streamedQueryOptions() collects a stream’s events, using TanStack Query’s experimental streamedQuery:

const events = useQuery(queryUtils.notifications.streamedQueryOptions());
events.data; // SseEvent<{ postId: string; message: string }>[] | undefined

const messages = useQuery(
	queryUtils.notifications.streamedQueryOptions({
		initialValue: "",
		reducer: (text, event) => `${text}${event.data.message}`,
	}),
);
messages.data; // string | undefined

Query Keys

key() matches every query under a node, to invalidate them:

queryClient.invalidateQueries({ queryKey: queryUtils.key() }); // everything
queryClient.invalidateQueries({ queryKey: queryUtils.posts.key() }); // every posts route
queryClient.invalidateQueries({ queryKey: queryUtils.posts.get.key() }); // every posts.get query

queryKey(), infiniteQueryKey(), streamedQueryKey() and mutationKey() give one query’s key, typed with its data:

const postKey = queryUtils.posts.get.queryKey({ params: { id: "post_1" } });
// ["posts", "get", { params: { id: "post_1" } }]

queryClient.setQueryData(postKey, (current) =>
	current?.status === 200
		? { ...current, body: { ...current.body, title: "Edited" } }
		: current,
);
  • A key is the route’s path in the tree, then the request.
  • Without a request, they return the key of every query of that kind for the route.
  • Pass queryKey in the options to use your own key instead.

Key Prefix

Keys hold the route and request, not what the client adds to every request. When such a value changes responses, such as a locale header, add it to every key with prefix, so different values don’t share cache entries:

const createQueryUtils = (locale: string) =>
	createTanstackQueryUtils(
		createClient(getContract(), {
			globalHeaders: { "accept-language": locale },
		}),
		{ prefix: ["locale", locale] },
	);

Direct Calls

Each util also has fetch(), which calls the route like the client:

const { body: post } = await queryUtils.posts.get.fetch({
	params: { id: "post_1" },
});

Was this page helpful?