@contract-kit/react-query
v1.0.0
Published
TanStack Query integration for contract-kit
Downloads
970
Maintainers
Readme
@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.
Installation
npm install @contract-kit/react-query @contract-kit/client @contract-kit/core @tanstack/react-query reactTypeScript requirements
This package requires TypeScript 5.0 or higher for proper type inference.
Setup
1. Create your client
// lib/api-client.ts
import { createClient } from "@contract-kit/client";
export const apiClient = createClient({
baseUrl: "https://api.example.com",
headers: async () => ({
Authorization: `Bearer ${getToken()}`,
}),
});2. Create the React Query adapter
// lib/rq.ts
import { createReactQuery } from "@contract-kit/react-query";
import { apiClient } from "./api-client";
export const rq = createReactQuery(apiClient);3. Set up QueryClientProvider
// app/providers.tsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
const queryClient = new QueryClient();
export function Providers({ children }) {
return (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
);
}Usage
Options-first API (recommended)
The options-first API generates options objects that can be used with any TanStack Query primitive.
Query options
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 <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>{data.title}</h1>
<p>Completed: {data.completed ? "Yes" : "No"}</p>
</div>
);
}Prefetching
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 <div>{/* ... */}</div>;
}Server-side data fetching
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 (
<HydrationBoundary state={dehydrate(queryClient)}>
<TodoDetail id={params.id} />
</HydrationBoundary>
);
}Mutation options
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { rq } from "@/lib/rq";
import { createTodo, listTodos } 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: rq(listTodos).key() });
},
});
const mutation = useMutation(createTodoMutation);
const handleSubmit = (data: { title: string }) => {
mutation.mutate({ body: data });
};
return (
<form onSubmit={handleSubmit}>
{/* form fields */}
<button disabled={mutation.isPending}>
{mutation.isPending ? "Creating..." : "Create Todo"}
</button>
</form>
);
}Infinite query options
import { useInfiniteQuery } from "@tanstack/react-query";
import { rq } from "@/lib/rq";
import { listTodos } from "@/contracts/todos";
function InfiniteTodoList() {
const todosInfiniteQuery = rq(listTodos).infiniteQueryOptions({
query: { status: "open" },
page: ({ pageParam }) => ({
query: { cursor: pageParam ?? null },
}),
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
initialPageParam: null,
});
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =
useInfiniteQuery(todosInfiniteQuery);
return (
<div>
{data?.pages.map((page) =>
page.items.map((todo) => <div key={todo.id}>{todo.title}</div>)
)}
<button
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
>
{isFetchingNextPage ? "Loading more..." : "Load More"}
</button>
</div>
);
}API reference
createReactQuery(client)
Creates a React Query adapter factory.
const rq = createReactQuery(apiClient);rq(contract)
Creates a contract helper with query/mutation options methods.
const helper = rq(getTodo);helper.queryOptions(options)
[Recommended] Generate query options that can be passed to any TanStack Query primitive.
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);helper.mutationOptions(options)
[Recommended] Generate mutation options that can be passed to useMutation.
const mutationOpts = helper.mutationOptions({
// ...any TanStack Query mutation options (onSuccess, onError, retry, etc.)
});
useMutation(mutationOpts);helper.infiniteQueryOptions(options)
[Recommended] Generate infinite query options for pagination.
const infiniteOpts = helper.infiniteQueryOptions({
path?: { ... }, // Static path params included in the cache key
query?: { ... }, // Static query params included in the cache key
page?: (ctx: { pageParam }) => ({
path?: { ... }, // Page-specific path params
query?: { ... }, // Page-specific query params (cursor, offset, etc.)
}),
initialPageParam: ...,
getNextPageParam: (lastPage) => ...,
getPreviousPageParam: (firstPage) => ...,
key?: readonly unknown[], // Optional custom query key
// ...any other TanStack Query infinite query options
});
useInfiniteQuery(infiniteOpts);If you need fully dynamic params, pass a custom key and use params(...) instead:
const infiniteOpts = helper.infiniteQueryOptions({
key: ["todos", { status: "open" }],
params: ({ pageParam }) => ({
query: { status: "open", cursor: pageParam ?? null },
}),
initialPageParam: null,
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
});helper.key(params?)
Generate a stable query key for cache operations.
helper.key(); // ["contractName"]
helper.key({ path: { id: "1" } }); // ["contractName", { path: { id: "1" } }]helper.endpoint
Access the underlying endpoint for manual calls.
const data = await helper.endpoint.call({ path: { id: "123" } });Type inference
All options are fully typed based on your contracts:
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
React Query errors are typed from the endpoint contract, including declared catalog errors and non-2xx response bodies:
const todo = rq(getTodo);
const { error } = useQuery(todo.queryOptions({ path: { id: "123" } }));
if (todo.endpoint.isError(error, { code: "TODO_NOT_FOUND" })) {
console.log(error.details); // typed from the catalog details schema
} else if (error) {
console.log(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):
const { data } = rq(getTodo).useQuery({ path: { id } });After (options-first):
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/nuqs- URL query state integration@contract-kit/react-hook-form- Form integration
License
MIT
