npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@contract-kit/react-query

v0.1.2

Published

TanStack Query integration for contract-kit

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 react

TypeScript 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

License

MIT