React-Query 4 use cases for REST

Artem Deikun
FED is love — Front-End
3 min readAug 28, 2022

--

Library React-Query is one of the best solutions in React ecosystem for handling Requests/Responses.

In this article, I share instructions for integration on the existing projects and some samples of how to use react-query in a few scenarios for the REST API.

Install and integrate:

Include in the application as dependency react-query NPM package:

npm i -S react-query

Create an instance of QueryClient:

const queryClient = new QueryClient();

Wrap part of the application that will use react-query with the QueryClientProvider component and pass with client property the instance of QueryClient class.

Let’s implement REST cases:

  1. GET request to /list/ that returns a list of items
  2. POST request to /list/123 that creates an item with the ID 1 and pass some details in the body payload
  3. PUT request to /list/123 that updates an item 123with the payload.
  4. GET request to /list/123 that returns the details of an item 123
  5. DELETE request to/list/123 deletes item 123

REST samples:

1. GET
Request to /list/ that returns a list of items

const { data, isError, isLoading } = 
useQuery(['list'], async () => (await axios.get('/api/list')).data);

Alternative code with Promises:

const { data: studentsList } = 
useQuery(['list'], () =>
axios.get(`/api/list`).then(({ data }) => data)
);

1.1. GET with

In case of adding some filters to GET request:

const { data, isError, isLoading } = 
useQuery(['list'], async () => (
await axios.get('/api/list', { params: { category: 'value' } }
))?.data);

2. POST
Request to /list/123 that creates an item with the ID 1 and pass some details in the body payload

const {mutate, isLoading, isError, isSuccess, mutate} = useMutation((id, payload) => axios.post('/todos/' + id, payload));

In any place, you can call mutate method for sending a request like:

<button onClick={() => mutate(123, { message: 'World' })}></button>

3. PUT
Request to /list/123 that updates an item with the ID 1 and pass some details in the body payload.

const {mutate, isLoading, isError, isSuccess, mutate} = useMutation((id, payload) => axios.put('/todos/' + id, payload));

In any place, you can call mutate method for sending a request like:

<input onChange={() => mutate(123, { title: 'Hello' })}></button>

Real implementation fetching REST/GET in React

  1. Import dependencies.
  2. Get an object from useQuery and destructure that for
    loading, errors, and data.
  3. The function callback for useQuery will be executed on the component mount and returns a Promise that is fulfilled with a value of the data key
    from Axios Response.
  4. Create conditions for handling errors and loading states.
  5. Render the list of items from the data prop from the React-Query hook.
https://gist.github.com/artemhp/382aa737e801a5bd4f3fcfb039cce92f

Real implementation submitting data REST/POST in React

  1. Import dependencies.
  2. Get an object-state from useQuery and destructure that for
    loading, errors, mutation.
  3. The function callback for useQuery will be executed when you needed and returns a Promise that is fulfilled with a value of the data key
    from Axios Response.
  4. In the function, the callback parameter is often used for payload for post/put methods.
  5. Handle loading and error state.
  6. Render the form. On submit trigger mutate function.
https://gist.github.com/artemhp/02065a97d5575198c5d27e3f2b1c823d

Summary

In this article typical REST tasks have been implemented.
But React-Query is not just a tool for async request handling but nice asynchronous state management that I recommend using across different projects.

--

--