2.2.4 • Published 6 months ago

react-api-query v2.2.4

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

🌸 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

2.2.1

7 months ago

2.2.3

7 months ago

2.2.2

7 months ago

2.2.4

6 months ago

2.2.0

7 months ago

2.1.2

1 year ago

2.1.1

1 year ago

2.0.2

1 year ago

2.1.0

1 year ago

2.0.1

1 year ago

2.0.0-next.2

2 years ago

2.0.0-next.3

2 years ago

2.0.0-next.1

2 years ago

2.0.0

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago