---
title: TanStack Query
description: Typed query and mutation options for TanStack Query.
---

```package-install
npm i @rest-rpc/tanstack-query
```

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

```ts client.ts
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

```tsx
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](/docs/client/fetch-client#per-call-options).
  TanStack Query passes the `signal` itself.
- Pass `skipToken` as `request` to disable a query, typed.
- `error` is typed like [`safe()`](/docs/errors#with-safe)'s, so narrow it
  with `isDefinedError()`.

## Infinite Queries

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

```tsx
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](/docs/server-sent-events)
events, using TanStack Query's experimental `streamedQuery`:

```tsx
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:

```ts
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:

```ts
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.

:::error[Reserved key]
`key` can't be a route or group name in a client passed to
`createTanstackQueryUtils()`. Using it is a type error.
:::

### 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:

```ts
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:

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