APIs & ReactJS - Untangle the complexities of Data Fetching with React Query

 




If you are a React developer, dealing with APIs is a common task to do, be that fetching data from the server or posting, updating or deleting data in it. Fetching and displaying data is a crucial part of any consumer facing web applications or site.

Regardless, fetching data from the server in a React application might be redundant and tedious every time a new component needs server data. This can harden the maintenance of a clean codebase. 

Axios is a popular data fetching library that offers us with advantages like vast browser compatibility, easy error handling, automatic JSON transformation and more. While Axios is really a prominent tool for HTTP requests, it still requires a significant amount of boilerplate code for each request, hence creation of clattered codebase. 

Being the savior, comes React Query, the missing data fetching library for web application present by Tanstack team. It eliminates the need to write repetitive boilerplate codes. React Query also offers out-of-the box support with built in Hooks, paginations, infinite data fetching, lazy loading and more. On top of that, it allows the collaborative use of Axios or any other popular libraries. 

So, without any further delay, let's drive into the realm of React Query.

Setting Up the React Project: 

Let's first set up a ReactJS project with Vite. If you are not familiar with it, you can read my article about Initialising a ReactJS project with Vite.

Get started with React Query: 

React query doesn't come with the default React setup, so install it with the following command: 


npm install @tanstack/react-query

Also install axios inside the project 


npm install axios

Inside the index.js file initialise a new instance of QueryClient and wrap the App component with a QueryClientProvider component with the newly initialised queryClient as the client. 


import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

const queryClient = new QueryClient(); // initialise a query client instance

ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
{/* wrap the whole project with QueryClientProvider component and pass
the initialised queryClient as client */}
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>


Now create a simple functional component where we will play with the freshly installed library (in my case I named it as FetchData.jsx).



import React from 'react'

const FetchData = () => {
return (
<div>
</div>
)
}

export default FetchData



Let's import axios inside this component and create a function to initiate the data fetching:



import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import React from "react";

const FetchData = () => {
// initialise the fetcher function
const fethData = () => {
return axios.get("https://catfact.ninja/fact");
};

return <div></div>;
};

export default FetchData;


Now, let's use the inbuilt hook useQuery provided by React Query for fetching data.



import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import React from "react";

const FetchData = () => {
// initialise the fetcher function
const fethData = () => {
return axios.get("https://catfact.ninja/fact");
};

// initialise useQuery hook for data fetching
const { isLoading, isError, error, data } = useQuery({
queryFn: fethData,
queryKey: ["quotes"],
});

return <div></div>;
};

export default FetchData;


The useQuery hook returns a lot of usable keys and methods that ease the process of handle loading state, error state, caching etc. Here, I have used 4 most common keys - isLoading, isError, error, and data.

  • isLoading: Returns TRUE while the data is loading from the server and FALSE when the data has been loaded successfully or an error occurred.
  • isError: Returns TRUE if any error occurred while fetching data from the server.
  • error: Returns the error details when an error happens.
  • data: This the data returned by the server when the fetching is successful.
Now, let's declare some tasks to do when any of the mentioned logic happens.


import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import React from "react";

const FetchData = () => {
// initialise the fetcher function
const fethData = () => {
return axios.get("https://catfact.ninja/fact");
};

// initialise useQuery hook for data fetching
const { isLoading, isError, error, data } = useQuery({
queryFn: fethData,
queryKey: ["quotes"],
});

// do if the data is loading
if (isLoading) return "Loading Data... Please wait...";

// do if there is an error
if (isError) return error.message;

// if data fetching is successful console the data
console.log(data);
return <div></div>;
};

export default FetchData;


The data returned from the server is structured differently based on how the server is sending the data.
we have used a public api that returns interesting facts about cat. In our case, the data can be retrieved by data.data.fact as the data is a nested object. 

Let's show the data inside a paragraph in the application.


import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import React from "react";

const FetchData = () => {
// initialise the fetcher function
const fethData = () => {
return axios.get("https://catfact.ninja/fact");
};

// initialise useQuery hook for data fetching
const { isLoading, isError, error, data } = useQuery({
queryFn: fethData,
queryKey: ["quotes"],
});

// do if the data is loading
if (isLoading) return "Loading Data... Please wait...";

// do if there is an error
if (isError) return error.message;

// if data fetching is successful
console.log(data);
return (
<div>
<p>{data.data.fact}</p> // show the data in the frontend
</div>
);
};

export default FetchData;


So, this is how you can easily and effectively fetch data from the server with the help of Axios and react Query together by writing minimal code. This is just the basic data fetching operation, querying data can get much more complicated depending on the size of data and the structures. Luckily, React Query provides clean and beautiful solution for those complex processes too. We will learn about those together in upcoming posts. 

See you in another post. Have a nice day and a learning journey ahead.

Comments