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 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-api-query

v2.2.4

Published

React hooks to use TanStack Query with a typed API client.

Downloads

190

Readme

🌸 react-api-query

React hooks to use TanStack Query with a typed API client.

  • 🛡️ 100% Type-safe
  • 🕵️ IDE autocompletion
  • 🍃 Tiny footprint and no dependencies
  • 💕 Perfect match for typed OpenAPI or JSON-RPC

More types, less typing!

Assume you have an API like this:

const api = {
  async getUser(id: number) {
    const res = await fetch(`/api/users/${id}`);
    return (await res.json()) as User;
  },

  async deleteUser(id: number) {
    await fetch(`/api/users/${id}`, { method: "DELETE" });
  },
};

interface User {
  id: number;
  name: string;
  email: string;
}

Using this with react-query now becomes as easy as this:

import { apiHooks } from "react-api-query";
import api from "./api"; // Your typed API client

// Create React hooks for your API
const { useApiQuery, useApiMutation } = apiHooks(api);

function User({ id: number }: Props) {
  const query = useApiQuery("getUser", id);
  const deleteUser = useApiMutation("deleteUser");

  if (query.isLoading) return <div>Loading...</div>;

  return (
    <div>
      {user.name}
      <button
        disabled={deleteUser.isLoading}
        onClick={() => deleteUser(user.id)}
      >
        Delete
      </button>
    </div>
  );
}

Note: The query-keys are generated from the name of the API method you are calling and the arguments you pass.

Installation

npm install @tanstack/react-query react-api-query

Note Since V2, the module is published as ESM-only.

You can play with a live example over at StackBlitz:

Open in StackBlitz

API

The hooks are just thin wrappers around their counterparts in React Query. Head over to the official docs for a deep dive.

useApiQuery(method | opts, ...args)

Wrapper around useQuery where you don't need to provide a query key nor a query function. Instead, you pass the name of one of your API methods and the arguments your API expects.

If you don't need to provide any further query options, you can pass the method name as string.

Otherwise, you can pass an object that takes the same options as useQuery with an additional method property:

useApiQuery({ method: "getUser", staleTime: 1000 }, 42);

This will call api.getUser(42). Of course, all these arguments are properly typed, so you will get the correct autocompletion in your IDE.

Returns

The return value is the same as with useQuery, but provides the following additional methods for convenience:

update(updater)

Shortcut for calling queryClient.setQueryData(queryKey, updater)

invalidate()

Shortcut for calling queryClient.invalidateQueries(queryKey)

removeQuery()

Shortcut for calling queryClient.removeQueries(queryKey)

useInfiniteApiQuery(method, opts)

Wrapper around useInfiniteQuery where you don't need to provide a query key nor a query function. Instead, you pass the name of one of your API methods and the arguments your API expects.

useApiMutation(method, opts)

Wrapper around useMutation where you don't need to provide a mutation key nor a mutation function. Instead, you pass the name of one of your API methods.

Returns

The return value is an async function that calls mutateAsync under the hood and returns its promise.

While the result is a function, it still has all the return values of useMutation mixed in, like isLoading or isError:

const deleteUser = useApiMutation("deleteUser");
return (
  <button disabled={deleteUser.isLoading} onClick={() => deleteUser(user.id)}>
    Delete
  </button>
);

Prefetching

You can also create a prefetch method to pre-populate data outside your React components, for example inside your router:

import { prefetching } from "react-api-query";
import { api } from "./api";

const queryClient = new QueryClient();
const prefetch = prefetching(api, queryClient);

// A fictive loader function
async function loader(params) {
  await prefetch("getUser", params.id);
}

License

MIT