TanStack Query
Typed query and mutation options for TanStack Query.
npm install @rest-rpc/tanstack-querypnpm add @rest-rpc/tanstack-queryyarn add @rest-rpc/tanstack-querybun add @rest-rpc/tanstack-querynub add @rest-rpc/tanstack-queryaube add @rest-rpc/tanstack-querycreateTanstackQueryUtils() 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
selectreads itsbody. - Options take any TanStack Query option, plus
fetchOptionsfor the client’s per-call options. TanStack Query passes thesignalitself. - Pass
skipTokenasrequestto disable a query, typed. erroris typed likesafe()’s, so narrow it withisDefinedError().
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
queryKeyin 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" },
});