TanStack Query integration for Beignet
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.
npm install @beignet/react-query @beignet/core @tanstack/react-query react
This package requires TypeScript 5.0 or higher for proper type inference.
// lib/api-client.ts
import { createClient } from "@beignet/core/client";
export const apiClient = createClient({
baseUrl: "https://api.example.com",
headers: async () => ({
Authorization: `Bearer ${getToken()}`,
}),
});
// lib/rq.ts
import { createReactQuery } from "@beignet/react-query";
import { apiClient } from "./api-client";
export const rq = createReactQuery(apiClient);
// app/providers.tsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
const queryClient = new QueryClient();
export function Providers({ children }) {
return (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
);
}
The options-first API generates options objects that can be used with any TanStack Query primitive.
import { useQuery } from "@tanstack/react-query";
import { rq } from "@/client/rq";
import { getTodo } from "@/features/todos/contracts";
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>
);
}
import { useQueryClient } from "@tanstack/react-query";
import { rq } from "@/client/rq";
import { getTodo } from "@/features/todos/contracts";
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>;
}
import { QueryClient, dehydrate, HydrationBoundary } from "@tanstack/react-query";
import { rq } from "@/client/rq";
import { getTodo } from "@/features/todos/contracts";
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>
);
}
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { rq } from "@/client/rq";
import { createTodo, listTodos } from "@/features/todos/contracts";
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).contractKey() });
},
});
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>
);
}
import { useInfiniteQuery } from "@tanstack/react-query";
import { rq } from "@/client/rq";
import { listTodos } from "@/features/todos/contracts";
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>
);
}
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: { ... }, // Required when the contract has required path params
query?: { ... }, // Required when the contract has required query params
body?: { ... }, // Required when the contract has a required body
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.namespaceKey()Generate a namespace-level key for broad cache operations. Contracts created
from createContractGroup().namespace("todos") use that namespace.
Non-namespaced contracts use null so they cannot collide with a real
namespace string.
helper.namespaceKey(); // ["beignet", "todos"]
helper.contractKey()Generate a contract-level key without path, query, or body params.
helper.contractKey(); // ["beignet", "todos", "getTodo"]
helper.key(params?)Generate a stable query key for cache operations.
helper.key(); // ["beignet", "todos", "getTodo"]
helper.key({ path: { id: "1" } }); // ["beignet", "todos", "getTodo", { path: { id: "1" } }]
key(...) normalizes params the same way the client serializes them: null
and undefined object entries are omitted, while meaningful values like 0,
false, and empty strings are preserved. Request bodies are included in query
keys when passed to queryOptions(...).
These keys are plain TanStack Query keys, so prefix invalidation works as expected:
queryClient.invalidateQueries({ queryKey: rq(getTodo).namespaceKey() });
queryClient.invalidateQueries({ queryKey: rq(getTodo).contractKey() });
queryClient.invalidateQueries({
queryKey: rq(getTodo).key({ path: { id: "1" } }),
});
helper.endpointAccess the underlying endpoint for manual calls.
const data = await helper.endpoint.call({ path: { id: "123" } });
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 }
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);
}
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.
@beignet/core/contracts - Core contract definitions@beignet/core/client - HTTP client@beignet/nuqs - URL query state integration@beignet/react-hook-form - Form integrationMIT