How to Handle React Query Error Response in React 18

Last Updated on by in React JS

React Query error handling example. Error handling is a crucial task in dealing with data fetching.

React Query helps us to handle asynchronous data with utmost flexibility. It offers various hooks for creating, reading, updating, and deleting data from the database.

React Query is a wonderful module that makes error handling extremely simple by returning an error property.

This tutorial will teach you how to make a Get request with React query using the useQuery hook.

Most importantly make you understand how to easily handle error response after making the fetch request to the server.

React Query offers an error object that holds the error message; We will show the error message in our React app using the Bootstrap alert UI component.

How to Display Error Message in React JS using React Query

  • Step 1: Create React Project
  • Step 2: Install React Query and Axios Modules
  • Step 3: Setting Up Bootstrap
  • Step 4: Register React-Query in React
  • Step 5: Build Function Component
  • Step 6: Handle Error Response
  • Step 7: Update Global Component
  • Step 8: View App on Browser

Create React Project

You need to run the command on the terminal to create a brand new React project.

npx create-react-app react-blog-app

After the app is created, move into the project folder.

cd react-blog-app

Install React Query and Axios Modules

This project requires axios and react-query libraries to be added to the React project.

Run the command using the npm to install the modules.

npm install @tanstack/react-query axios --legacy-peer-deps

Setting Up Bootstrap

To style the React app we will install and use the Bootstrap library.

npm i bootstrap --legacy-peer-deps

The work is not done yet, you have to register the bootstrap CSS in the src/App.js file.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
function App() {
  return <div></div>;
}
export default App;

Register React-Query in React

The React query is installed, but to take the full advantage of the library you have to import the QueryClientProvider and QueryClient modules in the App.js file.

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
// Create a client
const queryClient = new QueryClient();
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>
);

Build Function Component

Head over to src folder, inside the src directory create the components/ folder, then create theUsers.js file.

import React from 'react'
function Users() {
  return (
    <div>Users page</div>
  )
}
export default Users

Handle Error Response

You have created the Users functional component, now we will show you how to make the fetch request using useQuery hook and at the same time how to handle the error and other response.

Make sure to add the following code to the components/Users.js file.

import React from "react";
import axios from "axios";
import { useQuery } from "@tanstack/react-query";
async function fetchData() {
  const { data } = await axios.get(
    "https://jsonplaceholder.typicode.com/users1"
  );
  return data;
}
function Users() {
  const { isLoading, isError, error, data } = useQuery(["users"], fetchData);
  if (isLoading) {
    return <div className="alert alert-warning">Retrieving Data ...</div>;
  }
  if (isError) {
    return (
      <div>
        <div className="alert alert-danger">{error.message}</div>
      </div>
    );
  }
  return (
    <ul className="list-group">
      {data.map((res, index) => {
        return (
          <li className="list-group-item mb-3" key={index}>
            <h3>{res.username}</h3>
            <p>{res.email}</p>
          </li>
        );
      })}
    </ul>
  );
}
export default Users;

Update Global Component

We have almost done with the function component and the React query, the ultimate task is to add the Users component to the App.js file.

import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import Users from "./components/Users";
function App() {
  return (
    <div className="container mt-5">
      <h2 className="mb-4">React Query Error Handling Example</h2>
      <Users />
    </div>
  );
}
export default App;

View App on Browser

Our app is almost ready, next things is to invoke the React development server using the following command.

npm start

You need to paste the given url on the browser’s address bar in order to view the app on the browser.

http://localhost:3000

How to Handle React Query Error Response in React JS

Conclusion

In this tutorial, we learned how to get an error message in contrast with React query fetch request.

We saw how to work with isError and error properties returned by the useQuery hook.

Error object provides a simple mechanism for handling errors in React app driven by React query.

After requesting the server, a response is always expected; It could be a success or an error.

If somehow some error occurs. We can take the help of the error property and show the error message to the user.

Age calculator tool

🎂✨ Discover your age in detail and with countdown to your next birthday with fun facts! 🎈🎉

Calculate your age now!
Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.