@contract-kit/react-query
v0.1.2
Published
TanStack Query integration for contract-kit
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 { createRQ } from "@contract-kit/react-query";
import { apiClient } from "./api-client";
export const rq = createRQ(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 } 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 (
<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({
params: ({ 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
createRQ(client)
Creates a React Query adapter factory.
const rq = createRQ(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({
onSuccessInvalidate?: boolean | ((vars) => string[] | readonly unknown[][]),
// ...any other TanStack Query mutation options
});
useMutation(mutationOpts);helper.infiniteQueryOptions(options)
[Recommended] Generate infinite query options for pagination.
const infiniteOpts = helper.infiniteQueryOptions({
params: (ctx: { pageParam }) => ({
path?: { ... },
query?: { ... },
}),
initialPageParam: ...,
getNextPageParam: (lastPage) => ...,
getPreviousPageParam: (firstPage) => ...,
// ...any other TanStack Query infinite query options
});
useInfiniteQuery(infiniteOpts);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
Errors are typed as ContractError:
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):
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/react-hook-form- Form integration
License
MIT
