Beignet API reference
    Preparing search index...

    Module @beignet/react-query

    @beignet/react-query

    TanStack Query integration for Beignet

    Caution

    Beignet is experimental alpha software. The 0.0.x package line is for early evaluation, and APIs may change between releases while the framework settles.

    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.

    This package ships a TanStack Intent skill for coding agents: @beignet/react-query#client. Load it when adding typed client setup, React Query options, infinite queries, feature client helpers, hooks, cache keys, cache invalidation, server prefetching, idempotent mutations, or client/server boundary fixes in a Beignet app.

    import { createClient } from "@beignet/core/client";
    import { createReactQuery } from "@beignet/react-query";
    import { QueryClient } from "@tanstack/react-query";

    export const apiClient = createClient({
    baseUrl: "https://api.example.com",
    headers: async () => ({
    Authorization: `Bearer ${getToken()}`,
    }),
    });

    export const rq = createReactQuery(apiClient);

    export function makeQueryClient() {
    return new QueryClient();
    }
    // app/providers.tsx
    import { QueryClientProvider } from "@tanstack/react-query";
    import { type ReactNode, useState } from "react";
    import { makeQueryClient } from "@/client";

    export function Providers({ children }: { children: ReactNode }) {
    const [queryClient] = useState(() => makeQueryClient());

    return (
    <QueryClientProvider client={queryClient}>
    {children}
    </QueryClientProvider>
    );
    }

    Keep root client/ for shared adapter setup, then put feature-specific query options, mutation options, invalidation helpers, and hooks under features/<feature>/client/:

    // features/todos/client/queries.ts
    import type { QueryClient } from "@tanstack/react-query";
    import { rq } from "@/client";
    import { createTodo, listTodos } from "@/features/todos/contracts";

    export function listTodosQueryOptions() {
    return rq(listTodos).queryOptions({ query: {} });
    }

    export function createTodoMutationOptions() {
    return rq(createTodo).mutationOptions();
    }

    export function invalidateTodos(queryClient: QueryClient) {
    return rq(listTodos).invalidate(queryClient);
    }

    Components can import those helpers and keep UI state separate from cache-key construction:

    import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
    import {
    createTodoMutationOptions,
    invalidateTodos,
    listTodosQueryOptions,
    } from "@/features/todos/client/queries";

    function TodoList() {
    const queryClient = useQueryClient();
    const todosQuery = useQuery(listTodosQueryOptions());
    const createTodoMutation = useMutation({
    ...createTodoMutationOptions(),
    onSuccess: () => invalidateTodos(queryClient),
    });

    return <div>{/* ... */}</div>;
    }

    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";
    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";
    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 { dehydrate, HydrationBoundary } from "@tanstack/react-query";
    import { makeQueryClient, rq } from "@/client";
    import { getTodo } from "@/features/todos/contracts";

    export async function TodoPage({ params }: { params: { id: string } }) {
    const queryClient = makeQueryClient();

    // 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>
    );
    }

    That prefetch path uses the generated HTTP query function. In Next.js apps, ordinary { contract, useCase } routes can avoid an internal HTTP request by using a cached server-context helper plus a server-only prefetch helper that preserves the contract query key and replaces only the server queryFn:

    import { getTodoUseCase } from "@/features/todos/use-cases";
    import { getAppRequestContext } from "@/lib/server-context";
    import { serverUseCaseQueryOptions } from "@/lib/server-react-query";

    const ctx = await getAppRequestContext();
    const queryClient = makeQueryClient();

    await queryClient.prefetchQuery(
    serverUseCaseQueryOptions(
    rq(getTodo).queryOptions({ path: { id: params.id } }),
    getTodoUseCase,
    ctx,
    { id: params.id },
    ),
    );

    Use the use-case path only when the use case output is the contract success body. Use the HTTP rq(...) path when the route handler owns response mapping, headers, streaming, or other HTTP-layer behavior.

    import { useMutation, useQueryClient } from "@tanstack/react-query";
    import { rq } from "@/client";
    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 every cached listTodos call.
    rq(listTodos).invalidate(queryClient);
    },
    });

    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>
    );
    }

    For contracts that follow the Beignet cursor pagination convention — an optional cursor query param and a PageResult response with page.nextCursor — spread cursorPagination() into the options:

    import { useInfiniteQuery } from "@tanstack/react-query";
    import { cursorPagination } from "@beignet/react-query";
    import { rq } from "@/client";
    import { listTodos } from "@/features/todos/contracts";

    function InfiniteTodoList() {
    const todosInfiniteQuery = rq(listTodos).infiniteQueryOptions({
    query: { status: "open" },
    ...cursorPagination(),
    });

    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>
    );
    }

    data.pages is typed per page: the infinite options observe InfiniteData of the contract response. Contracts without a cursor query param or without page.nextCursor in the response fail to typecheck at the spread site.

    Contracts that paginate differently pass initialPageParam, getNextPageParam, and page(...) by hand:

    const todosInfiniteQuery = rq(listTodos).infiniteQueryOptions({
    query: { limit: 10 },
    initialPageParam: 0,
    page: ({ pageParam }) => ({
    query: { offset: pageParam },
    }),
    getNextPageParam: (lastPage) =>
    lastPage.page.hasMore
    ? lastPage.page.offset + lastPage.items.length
    : undefined,
    });

    Creates a React Query adapter factory.

    const rq = createReactQuery(apiClient);
    

    Headers are excluded from generated query keys by default because persisted caches would otherwise store credentials such as Authorization tokens. When a non-secret request-shaping header changes response data, opt that specific header into keys with keyHeaders:

    const rq = createReactQuery(apiClient, {
    keyHeaders: ["X-Workspace-Preview"],
    });

    rq(listTodos).queryOptions({
    headers: { "X-Workspace-Preview": "workspace-1", Authorization: "Bearer ..." },
    });
    // queryKey: ["beignet", "todos", "listTodos", "GET /todos",
    // { headers: { "x-workspace-preview": "workspace-1" } }]

    Only whitelisted header names are included. Names are matched case-insensitively and stored lowercased in the key. Never whitelist credential headers; pass a per-call key when you need a fully custom key instead.

    Creates a contract helper with query/mutation options methods.

    const helper = rq(getTodo);
    

    [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
    headers?: { ... }, // Sent with the request; keyed only via keyHeaders
    key?: readonly unknown[], // Custom query key
    // ...any other TanStack Query options (staleTime, enabled, select, etc.)
    });

    // Use with any primitive
    useQuery(queryOpts);
    queryClient.prefetchQuery(queryOpts);
    queryClient.fetchQuery(queryOpts);
    queryClient.ensureQueryData(queryOpts);

    select threads through the options, so the observed data narrows while the generated queryFn still returns and caches the raw contract response:

    const { data } = useQuery(
    rq(getTodo).queryOptions({
    path: { id: "123" },
    select: (todo) => todo.title,
    }),
    );
    // data is typed as: string | undefined

    [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);

    For contracts with idempotency metadata, the generated mutationFn derives one idempotency key per variables object and keeps it stable across TanStack retry attempts, so retried requests replay instead of re-executing. Fresh variables objects passed to separate mutate(...) calls get distinct keys. Retry state is keyed by variables-object identity, so reusing the exact same object for a later intentional mutation also reuses its key. Pass idempotencyKey in the mutation variables when multiple invocations should be one logical command:

    mutation.mutate({ body: { title: "New todo" }, idempotencyKey: key });
    

    Caveat: calling mutate() with no variables skips per-invocation key derivation and the client generates a fresh key per attempt. Pass a variables object when an idempotent mutation should keep its key across retries.

    [Recommended] Generate infinite query options for pagination. The options observe InfiniteData of the contract response, so useInfiniteQuery data has typed pages, and select narrows the observed data the same way as queryOptions.

    For contracts that follow the cursor convention, spread cursorPagination():

    const infiniteOpts = rq(listTodos).infiniteQueryOptions({
    query: { status: "open" },
    ...cursorPagination(),
    });

    useInfiniteQuery(infiniteOpts);

    For other pagination shapes, pass the page-param options by hand:

    const infiniteOpts = helper.infiniteQueryOptions({
    path?: { ... }, // Static path params included in the cache key
    query?: { ... }, // Static query params included in the cache key
    body?: { ... }, // Static body fields included in the cache key
    page?: (ctx: { pageParam }) => ({
    path?: { ... }, // Page-specific path params
    query?: { ... }, // Page-specific query params (cursor, offset, etc.)
    body?: { ... }, // Page-specific body fields (cursor, offset, etc.)
    }),
    initialPageParam: ...,
    getNextPageParam: (lastPage) => ...,
    getPreviousPageParam: (firstPage) => ...,
    key?: readonly unknown[], // Optional custom query key
    // ...any other TanStack Query infinite query options
    });

    useInfiniteQuery(infiniteOpts);

    For body-paginated contracts, such as a POST search endpoint, keep the stable filters in the static body and put the cursor in page(...).body. The static body is part of the cache key, and each page request sends the merged body:

    const searchOpts = rq(searchTodos).infiniteQueryOptions({
    body: { term: "beignet" },
    page: ({ pageParam }) => ({
    body: { cursor: pageParam ?? null },
    }),
    initialPageParam: null as string | null,
    getNextPageParam: (lastPage) => lastPage.page.nextCursor ?? undefined,
    });

    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.page.nextCursor ?? undefined,
    });

    Infinite-query options for contracts that follow the Beignet cursor pagination convention: an optional cursor query param on the request and a PageResult-style response with page.nextCursor (string | null). Spread the result into infiniteQueryOptions(...):

    import { cursorPagination } from "@beignet/react-query";

    useInfiniteQuery(
    rq(listTodos).infiniteQueryOptions({
    query: { status: "open" },
    ...cursorPagination(),
    }),
    );

    The first page is fetched without a cursor, each next page sends lastPage.page.nextCursor, and null tells TanStack Query there is no next page. Type safety is structural: contracts without a cursor query param or without page.nextCursor in the response fail to typecheck at the spread site.

    Generate a namespace-level key for broad cache operations. Contracts created from defineContractGroup().namespace("todos") use that namespace. Non-namespaced contracts use null so they cannot collide with a real namespace string.

    helper.namespaceKey(); // ["beignet", "todos"]
    

    Generate a contract-level key without path, query, or body params. The key includes the contract route ("GET /todos/:id"), so two contracts with the same derived local name but different routes — for example /v1/todos and /v2/todos list contracts — never share a cache key.

    helper.contractKey(); // ["beignet", "todos", "getTodo", "GET /todos/:id"]
    

    The route segment is also exposed as helper.route ("GET /todos/:id").

    Generate a stable query key for cache operations.

    helper.key();
    // ["beignet", "todos", "getTodo", "GET /todos/:id"]
    helper.key({ path: { id: "1" } });
    // ["beignet", "todos", "getTodo", "GET /todos/:id", { 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(...). Headers are excluded unless the adapter opted in with createReactQuery(client, { keyHeaders }).

    Generate TanStack Query filters for every contract in the helper's Beignet namespace.

    queryClient.invalidateQueries(helper.namespaceFilter());
    queryClient.invalidateQueries(helper.namespaceFilter({ stale: true }));

    Generate TanStack Query filters for every cached call to this contract.

    queryClient.invalidateQueries(helper.contractFilter());
    

    Generate TanStack Query filters for one contract call or parameter prefix.

    queryClient.invalidateQueries(
    helper.filter({ path: { id: "1" } }, { exact: true }),
    );

    These filters wrap plain TanStack Query keys, so prefix invalidation works as expected while TanStack Query still owns cache behavior:

    queryClient.invalidateQueries(rq(getTodo).namespaceFilter());
    rq(getTodo).invalidate(queryClient);
    rq(getTodo).invalidate(queryClient, { path: { id: "1" } });

    Use the smallest filter that matches the data you want to refresh:

    Helper Scope
    namespaceFilter() Every contract in one Beignet namespace.
    contractFilter() Every cached call for one contract.
    filter({ path, query, body }) One parameter-scoped contract key.

    Invalidate cached data for one contract using the helper's generated filters. With no params it invalidates every cached call to the contract. Pass params to target a detail key or parameter prefix.

    await rq(listTodos).invalidate(queryClient);
    await rq(getTodo).invalidate(queryClient, { path: { id: "1" } });

    For list writes, invalidate the contract key so every filtered or paginated list result refreshes:

    const createTodoMutation = useMutation(
    rq(createTodo).mutationOptions({
    onSuccess: () => {
    rq(listTodos).invalidate(queryClient);
    },
    }),
    );

    For detail writes, update or invalidate the exact detail key and then invalidate affected list contracts:

    const updateTodoMutation = useMutation(
    rq(updateTodo).mutationOptions({
    onSuccess: (_todo, vars) => {
    rq(getTodo).invalidate(queryClient, { path: vars.path });
    rq(listTodos).invalidate(queryClient);
    },
    }),
    );

    Access 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.

    MIT

    ReactQueryContractHelper
    ContractInfiniteQueryOptionsResult
    ContractQueryContractKey
    ContractQueryFilter
    ContractQueryFilterOptions
    ContractQueryKey
    ContractQueryKeyParams
    ContractQueryNamespaceKey
    ContractQueryOptionsResult
    ContractUseMutationOptions
    ContractUseQueryOptions
    CreateReactQueryOptions
    createReactQuery
    cursorPagination