Just a small collection of hooks that make it easy to integrate React Query into a REST API

Last update: May 7, 2022

React Query RESTful

react-query-restful is just a small collection of hooks that make it easy to integrate React Query into a REST API.

For a better understanding of the library, it is recommended to understand how React Query works.

Compatible with React Native.

Installing

Install with npm or yarn

npm:

npm i --save react-query-restful

yarn

yarn add react-query-restful

Inicialization

); }">
import { RestClientProvider } from "react-query-restful";

export default function App() {
  return (
    <RestClientProvider baseUrl="http://localhost:3000/api/">
      <Example />
    </RestClientProvider>
  );
}

Query usage

{data.name}

{data.description}

👀 {data.subscribers_count}{" "} ✨ {data.stargazers_count}{" "} 🍴 {data.forks_count}
); }">
import { buildQuery } from "react-query-restful";

export const getUsersQuery = buildQuery({ path: "users" });

function Example() {
  // GET http://localhost:3000/api/users
  const { isLoading, error, data } = getUsersQuery();

  // OR GET http://localhost:3000/api/users/1/vehicles?page=1
  /* const { isLoading, error, data } = getUsersQuery({
    appendToUrl: "1/vehicles",
    params: {
      page: 1,
    },
    options: {
      // Options from react-query
      retry: 2,
    },
  }); */

  if (isLoading) return "Loading...";

  if (error) return "An error has occurred: " + error.message;

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.description}</p>
      <strong>👀 {data.subscribers_count}</strong>{" "}
      <strong> {data.stargazers_count}</strong>{" "}
      <strong>🍴 {data.forks_count}</strong>
    </div>
  );
}

Mutation usage

The buildMutation method will return a few functions, the name will be based on the informed paths.

Example, the path users will generate the following functions:

  • createUserMutation (for POST request)
  • updateUserMutation (for PATCH request)
  • deleteUserMutation (for DELETE request)
  • replaceUserMutation (for PUT request)

All will share the same path & configuration.

Hello there!

); }">
import { buildMutation } from "react-query-restful";

export const {
  createUserMutation,
  updateUserMutation,
  deleteUserMutation,
  replaceUserMutation,
} = buildMutation({
  path: "users",
});

function Example() {
  const createUser = createUserMutation();

  /* OR
  const createUser = createUserMutation({
    invalidatePaths: ["products"],
    options: {
      // Options from react-query
      retry: 2,
    },
  }); */

  async function handleSubmit() {
    /**
     * POST /users {
     *  name: "John Doe"
     * }
     */
    await createUser.mutateAsync({
      data: {
        name: "John Doe",
      },
    });

    /**
     * POST /users/1/vehicles {
     *  plate: "XXXXX"
     * }
     */
    await createUser.mutateAsync({
      appendToUrl: "1/vehicles",
      data: {
        plate: "XXXXX",
      },
    });
  }

  return (
    <div>
      <h1>Hello there!</h1>
    </div>
  );
}

Caching and Authentication

You can cache the mutation / query result using the cacheResponse property.

Example:

export const { createSignInMutation } = createMutation({
  path: ["auth", "sign-in"], // Same as `baseUrl/auth/sign-in`
  cacheResponse: {
    key: "user",
  },
});

Assuming that the response contains the user data with the accessToken property, you can use the getSimpleJwtAuth function to set the Authorization header with the Bearer prefix. You must specify the key where it's stored in the cache, and the path until the token.

{children} ); };">
const App = ({ children }) => {
  return (
    <RestClientProvider
      baseUrl="http://localhost:3000/api/"
      {...getSimpleJwtAuth({ key: "user", path: "data.user.accessToken" })}
    >
      {children}
    </RestClientProvider>
  );
};

You can make your own custom authentication logic, example:

({ interceptors: { onRequest: async (config: any) => { const cachedToken = await AsyncStorage.getItem("token"); if (cachedToken && config.headers) { const parsedToken = JSON.parse(cachedToken); config.headers.Authorization = `Bearer ${token}`; } return config; }, }, });">
import { AsyncStorage } from "react-query-restful";

export const myOwnLogic = () => ({
  interceptors: {
    onRequest: async (config: any) => {
      const cachedToken = await AsyncStorage.getItem("token");

      if (cachedToken && config.headers) {
        const parsedToken = JSON.parse(cachedToken);

        config.headers.Authorization = `Bearer ${token}`;
      }

      return config;
    },
  },
});

And then pass it to the provider:

{children} ); };">
const App = ({ children }) => {
  return (
    <RestClientProvider baseUrl="http://localhost:3000/api/" {...myOwnLogic()}>
      {children}
    </RestClientProvider>
  );
};

Auto invalidation feature

Mutations are automatically invalidating the queries that shared the same path, to disable this, pass a falsy autoInvalidation in the RestClientProvider.

Mutation properties

Property Description Required
path A string or a array of string that will be appended to the baseUrl. true
invalidatePaths A array of strings that will be used to invalidate the queries after a successful mutation call. false
cacheResponse A object with the key that will be used to cache the response. false
options A object with the options from react-query. false

When calling the result of the build at component level, you can pass again theses properties, but all now will be optional.

And when calling the methods mutateAsync or mutate from mutation, you can pass the following properties:

Property Description Required
data A object with the data to be sent in the request body. false
appendToUrl A string that will be appended to the baseUrl. false

Query properties

Property Description Required
path A string or a array of string that will be appended to the baseUrl. true
invalidatePaths A array of strings that will be used to invalidate the queries after a successful mutation call. false
cacheResponse A object with the key that will be used to cache the response. false
options A object with the options from react-query. false
appendToUrl A string that will be appended to the baseUrl. false
params A object with the params that will be appended to the url. false

When calling the result of the build at component level, you can pass again theses properties, but all now will be optional.

Provider properties

Property Description Required
baseUrl A string with the base url. true
axiosConfig A object with the axios config. false
clientConfig A object with the React-Query Client config. false
autoInvalidation A boolean that will enable or disable auto invalidation. false
interceptors A object with a few interceptors that will be attached to axios. false

Running the tests

yarn && yarn test

Contributing

Feel free to submit a PR.

Authors

See also the list of contributors who participated in this project.

Thanks to Anurag Hazra for the TypeScript magic =).

License

This project is licensed under the MIT License - see the LICENSE file for details

GitHub

https://github.com/quasardd/react-query-restful
You might also like...

An implementation of React v15.x that optimizes for small script size

react-lite Introduction react-lite is an implementation of React that optimizes for small script size. Note: react-lite dose not support React v16.x n

May 9, 2022

A small 3D game built with react-three-fiber

A small 3D game built with react-three-fiber

Avoid the cubes while the speed progressively increases! Can you beat the rainbow level? The game is inspired by an old flash game I used to play in t

May 11, 2022

Small React three fiber multiplayer template

Small React three fiber multiplayer template

R3F.Multiplayer React three fiber, socket.io boilerplate multiplayer server and client 💻 Getting started Getting started To quickly get started Clone

May 4, 2022

Github-repository-metrics - A simple and small react component can check your repository stars and change theme on light/dark

Github-repository-metrics - A simple and small react component can check your repository stars and change theme on light/dark

Repository metrics for react This beauty and easy (4KB) react component can help

Apr 20, 2022

genji is A small vue state management framewok by vue3 reactivity.

genji is A small vue state management framewok by vue3 reactivity.

genji is A small vue state management framewok by vue3 reactivity. Why calls genji ? It's inspired by Overwatch. Genji flings prec

Mar 13, 2022

rfxTree: a small prototype/weekend project to control addressable RGB christmas tree lights

rfxTree: a small prototype/weekend project to control addressable RGB christmas tree lights

rfxTree is a small prototype/weekend project to control addressable RGB Christma

Mar 31, 2022

Make your React Components aware of their width and height!

Make your React Components aware of their width and height!

Make your React Components aware of their width and/or height! Hyper Responsive Components! Performant. Easy to use. Extensive browser support. Suppor

May 12, 2022

React Translator is a Web Interface created for make the creation of locales.json more easier.

React Translator is a Web Interface created for make the creation of locales.json more easier. Theses locales files can be used in the package @oneforx/react-translator

Jan 6, 2022

Collection of transforms for jscodeshift related to `@types/react`

types-react-codemod Collection of transforms for jscodeshift related to @types/react. Getting started The codemod helps to fix potential TypeScript co

May 18, 2022
A React JS project to make age and gender prediction using Agify.io and Genderize.io. Only for practice use and just for fun~

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Jan 1, 2022
Description So you want to make a difference in the world. You definitely want to do more than just sign a petition
Description So you want to make a difference in the world. You definitely want to do more than just sign a petition

peticipate Description So you want to make a difference in the world. You definitely want to do more than just sign a petition. You have some awesome

Dec 7, 2021
:tada: React Universal Hooks : just use****** everywhere (Functional or Class Component). Support React DevTools!
:tada: React Universal Hooks : just use****** everywhere (Functional or Class Component). Support React DevTools!

react-universal-hooks React Universal Hooks : just use****** everywhere. Support React >= 16.8.0 Installation Using npm: $ npm install --save react-un

Apr 22, 2022
Frontend Mentor - REST Countries API with color theme switcher
 Frontend Mentor - REST Countries API with color theme switcher

Frontend Mentor - REST Countries API with color theme switcher

Apr 24, 2022
In this repo you will find the sample project where we dive deeper into the nuances of how hooks work, particularly in the context of the React render/rerender cycle.

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: ya

Jan 29, 2022
User-friendly query builder for React
User-friendly query builder for React

react-awesome-query-builder User-friendly React component to build queries. Inspired by jQuery QueryBuilder Using awesome Ant Design v4 for widgets No

May 12, 2022
Just a simple react iota prototype to send messages to the tangle through a web app
Just a simple react iota prototype to send messages to the tangle through a web app

REACT IOTA This is a test project of mine to get familiar with the iota.js library. The WebApp is build with react and let you send messages to the ta

Jun 10, 2021
Tutorial for using react query and supabase

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run

Jan 30, 2022
React Query for Firestore, that you can actually use in production, on every screen.

React Query for Firestore, that you can actually use in production, on every screen.

May 3, 2022
This is used for minting NFTs and getting metadata , token owner, wallet address assigned to an NFT, just check it out and enjoy

nft-minter A Heroku web server to easily mint non-fungible tokens via an API Example Configuration: Blockchain: Ethereum Testnet: Rinkeby Contract: ER

Apr 17, 2022