TanStack Query integration for contract-kit
npm install @contract-kit/react-query> TanStack Query integration for Contract Kit
This package provides options-first TanStack Query integration that's automatically typed based on your contracts. Generate queryOptions, mutationOptions, and infiniteQueryOptions that work with all TanStack Query primitives (useQuery, useMutation, useInfiniteQuery, prefetchQuery, fetchQuery, etc.) with full type inference.
``bash`
npm install @contract-kit/react-query @contract-kit/client @contract-kit/core @tanstack/react-query react
This package requires TypeScript 5.0 or higher for proper type inference.
`ts
// lib/api-client.ts
import { createClient } from "@contract-kit/client";
export const apiClient = createClient({
baseUrl: "https://api.example.com",
headers: async () => ({
Authorization: Bearer ${getToken()},`
}),
});
`ts
// lib/rq.ts
import { createRQ } from "@contract-kit/react-query";
import { apiClient } from "./api-client";
export const rq = createRQ(apiClient);
`
`tsx
// app/providers.tsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
const queryClient = new QueryClient();
export function Providers({ children }) {
return (
{children}
);
}
`
The options-first API generates options objects that can be used with any TanStack Query primitive.
#### Query Options
`tsx
import { useQuery } from "@tanstack/react-query";
import { rq } from "@/lib/rq";
import { getTodo } from "@/contracts/todos";
function TodoDetail({ id }: { id: string }) {
// Generate query options
const todoQuery = rq(getTodo).queryOptions({
path: { id },
staleTime: 30_000,
});
// Use with any TanStack Query primitive
const { data, isLoading, error } = useQuery(todoQuery);
if (isLoading) return
return (
Completed: {data.completed ? "Yes" : "No"}
#### Prefetching
`tsx
import { useQueryClient } from "@tanstack/react-query";
import { rq } from "@/lib/rq";
import { getTodo } from "@/contracts/todos";function TodoList() {
const queryClient = useQueryClient();
const handleHover = (id: string) => {
// Prefetch on hover using queryOptions
const todoQuery = rq(getTodo).queryOptions({
path: { id },
});
queryClient.prefetchQuery(todoQuery);
};
return
{/ ... /};
}
`#### Server-Side Data Fetching
`tsx
import { QueryClient, dehydrate, HydrationBoundary } from "@tanstack/react-query";
import { rq } from "@/lib/rq";
import { getTodo } from "@/contracts/todos";export async function TodoPage({ params }: { params: { id: string } }) {
const queryClient = new QueryClient();
// Fetch on the server
const todoQuery = rq(getTodo).queryOptions({
path: { id: params.id },
});
await queryClient.prefetchQuery(todoQuery);
return (
);
}
`#### Mutation Options
`tsx
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { rq } from "@/lib/rq";
import { createTodo } from "@/contracts/todos";function CreateTodoForm() {
const queryClient = useQueryClient();
// Generate mutation options
const createTodoMutation = rq(createTodo).mutationOptions({
onSuccess: (data, vars, onMutateResult, context) => {
// Invalidate queries
queryClient.invalidateQueries({ queryKey: ["todos"] });
},
});
const mutation = useMutation(createTodoMutation);
const handleSubmit = (data: { title: string }) => {
mutation.mutate({ body: data });
};
return (
);
}
`#### Infinite Query Options
`tsx
import { useInfiniteQuery } from "@tanstack/react-query";
import { rq } from "@/lib/rq";
import { listTodos } from "@/contracts/todos";function InfiniteTodoList() {
const todosInfiniteQuery = rq(listTodos).infiniteQueryOptions({
params: ({ pageParam }) => ({
query: { cursor: pageParam ?? null },
}),
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
initialPageParam: null,
});
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =
useInfiniteQuery(todosInfiniteQuery);
return (
{data?.pages.map((page) =>
page.items.map((todo) => {todo.title})
)}
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
>
{isFetchingNextPage ? "Loading more..." : "Load More"}
);
}
`API Reference
$3
Creates a React Query adapter factory.
`ts
const rq = createRQ(apiClient);
`$3
Creates a contract helper with query/mutation options methods.
`ts
const helper = rq(getTodo);
`$3
[Recommended] Generate query options that can be passed to any TanStack Query primitive.
`ts
const queryOpts = helper.queryOptions({
path?: { ... }, // Path parameters
query?: { ... }, // Query parameters
key?: readonly unknown[], // Custom query key
// ...any other TanStack Query options (staleTime, enabled, etc.)
});// Use with any primitive
useQuery(queryOpts);
queryClient.prefetchQuery(queryOpts);
queryClient.fetchQuery(queryOpts);
queryClient.ensureQueryData(queryOpts);
`$3
[Recommended] Generate mutation options that can be passed to
useMutation.`ts
const mutationOpts = helper.mutationOptions({
onSuccessInvalidate?: boolean | ((vars) => string[] | readonly unknown[][]),
// ...any other TanStack Query mutation options
});useMutation(mutationOpts);
`$3
[Recommended] Generate infinite query options for pagination.
`ts
const infiniteOpts = helper.infiniteQueryOptions({
params: (ctx: { pageParam }) => ({
path?: { ... },
query?: { ... },
}),
initialPageParam: ...,
getNextPageParam: (lastPage) => ...,
getPreviousPageParam: (firstPage) => ...,
// ...any other TanStack Query infinite query options
});useInfiniteQuery(infiniteOpts);
`$3
Generate a stable query key for cache operations.
`ts
helper.key(); // ["contractName"]
helper.key({ path: { id: "1" } }); // ["contractName", { path: { id: "1" } }]
`$3
Access the underlying endpoint for manual calls.
`ts
const data = await helper.endpoint.call({ path: { id: "123" } });
`Type Inference
All options are fully typed based on your contracts:
`ts
const { data } = useQuery(rq(getTodo).queryOptions({ path: { id: "123" } }));
// data is typed as: { id: string; title: string; completed: boolean }const mutation = useMutation(rq(createTodo).mutationOptions());
mutation.mutate({ body: { title: "New Todo" } });
// body is typed as: { title: string; completed?: boolean }
`Error Handling
Errors are typed as
ContractError:`ts
import type { ContractError } from "@contract-kit/client";const { error } = useQuery(rq(getTodo).queryOptions({ path: { id: "123" } }));
if (error) {
console.log(error.status); // HTTP status code
console.log(error.message); // Error message
}
`Migration from Hook-First API
If you were using the hook-first API, you can migrate to the options-first API:
Before (hook-first):
`tsx
const { data } = rq(getTodo).useQuery({ path: { id } });
`After (options-first):
`tsx
const { data } = useQuery(rq(getTodo).queryOptions({ path: { id } }));
`Hook wrappers have been removed—use the options-first API for all queries and mutations.
Related Packages
@contract-kit/core - Core contract definitions
- @contract-kit/client - HTTP client
- @contract-kit/react-hook-form` - Form integrationMIT