? react-api-query

Hooks to use react-query with a typed API client.

More types, less typing!

Assume you have a an API like this:

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

const client = {
  async getUsers() {
    const res = await fetch("/api/users");
    return (await res.json()) as User[];

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

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

import { apiHooks } from "react-api-query";

const { useApiQuery, useApiMutation } = apiHooks(client);

function Users() {
  const query = useApiQuery("getUsers");
  const deleteUser = useApiMutation("deleteUser");
  if (query.isLoading) return <div>Loading...</div>;
  return (
      {query.data.map((user) => (
        <li key={user.id}>
            onClick={() => deleteUser(user.id)}

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


npm install -S react-query react-api-query


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

const { useApiQuery, useApiMutation } = apiHooks(client);


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 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: "getUsers", staleTime: 1000 });


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


Shortcut for calling queryClient.setQueryData(queryKey, updater)


Shortcut for calling queryClient.invalidateQuerie(queryKey)


Shortcut for calling queryClient.removeQueries(queryKey)

useApiMutation(method, opts)

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


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


This library has been written with oazapfts in mind – a utility to create TypeScript clients from OpenAPI specs, but works with any kind of typed client interfaces.




View Github