TM#009 - Fetching Data using TanStack Queries
Introduction
Managing and fetching data through API calls has always been a complicated and challenging task, causing headaches for developers. The process becomes even more frustrating when dealing with debugging logic bugs that arise from using useEffect to handle these issues, Thankfully, some peeps who are lot smarter than me faced similar issues and created React Query or TanStack to resolve just that. Today, we will explore how TanStack Queries simplify this process, making it a breeze compared to the old struggles.
Installing and Setting Up TanStack Query
To start using React Query, you need to install it in your project. You can do this using either npm or yarn. Run the following command in your terminal to install it with npm or yarn:
npm i @tanstack/react-query
or
yarn add @tanstack/react-query
Once React Query is installed, you need to wrap your entire application in the QueryClientProvider component. This component provides an instance of the QueryClient to all the child components. The QueryClient is responsible for managing the data fetching and caching logic.
Here's an example of how to set up the QueryClientProvider in your application:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { QueryClientProvider, QueryClient } from '@tanstack/react-query';
const queryClient = new QueryClient();
ReactDOM.render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>,
document.getElementById('root')
);
Understanding the useQuery Hook
In React Query, the useQuery hook is used for fetching data from a server or API. It accepts an object with two important properties: queryKey and queryFn. The queryKey is a unique identifier for the query, while the queryFn is a function that returns a promise resolving to the data you want to fetch.
Here's an example of using the useQuery hook to fetch data:
import React from 'react';
import axios from 'axios';
import { useQuery } from '@tanstack/react-query';
function Home() {
const postQuery = useQuery({
queryKey: ['posts'],
queryFn: async () => {
const response = await axios.get('<https://jsonplaceholder.typicode.com/posts>');
const data = await response.data;
return data;
}
});
if (postQuery.isLoading) return <h1>Loading....</h1>;
if (postQuery.isError) return <h1>Error loading data!!!</h1>;
return (
<div>
<h1>Home</h1>
{postQuery.data.map((item) => (
<p key={item.id}>{item.title}</p>
))}
</div>
);
}
export default Home;
In this example, we define a useQuery hook with a queryKey of ['posts']. This queryKey acts as a unique identifier for this specific query. The queryFn is an asynchronous function that contains the logic for fetching data API. The fetched data is then returned. queryKey helps in automaticlly catching the data for us.
The postQuery object returned by the useQuery hook contains various states such as isLoading, isError, and isSuccess. These states represent the different stages of the data fetching process. The data property contains the fetched data.
领英推荐
Dealing with Stale Data
React Query provides options for handling stale data. Stale data refers to the data that has been fetched but may not be up-to-date. React Query automatically makes new fetch requests to update stale data.
You can control the behavior of stale data using the staleTime and refetchInterval options. The staleTime option specifies the duration in milliseconds after which the cached data becomes stale. The refetchInterval option sets the interval in milliseconds between each automatic fetch request.
Here's an example:
useQuery({
queryKey: ['...'],
queryFn: () => {...},
staleTime: 1000
});
In this example, the staleTime is set to 1000 milliseconds (1 second). After 1 second, the cached data will be considered stale, and React Query will automatically trigger a new fetch request to update it.
You can also use the refetchInterval option to control the time interval between each automatic fetch request:
useQuery({
queryKey: ['...'],
queryFn: () => {...},
refetchInterval: 6000
});
In this example, the refetchInterval is set to 6000 milliseconds (6 seconds). React Query will automatically trigger a new fetch request every 6 seconds to keep the data up-to-date.
Conclusion
In this article, we have Briefly discussed how to install and set up React Query in a React application. We have also learned how to use the useQuery hook to fetch data and handle different states during the data fetching process. Additionally, we discussed handling stale data using the staleTime and refetchInterval options provided by React Query. However, TanStack Query has many other useful features, like useMutation to post data, handling pagination etc., however discussing them here will make this article much longer than it should be, so I would highly recommend the following video from “Web Dev Simplified” after reading this article.
This article was written by Farrukh Ahmed , Co-founder and HR Executive at Antematter.io