React-Query 4 use cases for REST
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:
- GET request to
/list/
that returns a list of items - POST request to
/list/123
that creates an item with the ID1
and pass some details in the body payload - PUT request to
/list/123
that updates an item123
with the payload. - GET request to
/list/123
that returns the details of an item123
- DELETE request to
/list/123
deletes item123
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
- Import dependencies.
- Get an object from useQuery and destructure that for
loading, errors, and data. - 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. - Create conditions for handling errors and loading states.
- Render the list of items from the data prop from the React-Query hook.
Real implementation submitting data REST/POST in React
- Import dependencies.
- Get an object-state from useQuery and destructure that for
loading, errors, mutation. - 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. - In the function, the callback parameter is often used for payload for post/put methods.
- Handle loading and error state.
- Render the form. On submit trigger mutate function.
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.