How to use the React-Query library for polling data with a custom interval

  Arif Babu

         

  React JS



Image not found!!

React-Query is a powerful library for managing and caching asynchronous data in React applications. It provides a simple and efficient way to fetch and manage data, including polling data at custom intervals. Below is an example of how to use React-Query for polling data with a custom interval:

First, make sure you have React-Query installed in your project:

bash
npm install react-query

Then, you can create a custom hook to handle data fetching and polling using React-Query:

javascript
import { useQuery } from 'react-query'; const fetchData = async () => { const response = await fetch('YOUR_API_ENDPOINT'); if (!response.ok) { throw new Error('Failed to fetch data'); } return response.json(); }; const usePollingData = (interval) => { return useQuery('data', fetchData, { refetchInterval: interval, refetchIntervalInBackground: false, // Set to true if you want to poll even when the tab is in background staleTime: Infinity, // Set to Infinity to prevent automatic refetching when the data becomes stale }); }; export default usePollingData;

In this example, fetchData is an asynchronous function that fetches your data from the API. The usePollingData hook utilizes useQuery from React-Query to automatically fetch data at the specified interval.

Now, you can use this custom hook in your component:

javascript
import React from 'react'; import { usePollingData } from './usePollingData'; const MyComponent = () => { const { data, isLoading, error } = usePollingData(5000); // Polling interval set to 5 seconds (5000 milliseconds) if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; return ( <div> {/* Render your data here */} {data && ( <ul> {data.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul> )} </div> ); }; export default MyComponent;

In this component, we're using the usePollingData custom hook with an interval of 5000 milliseconds (5 seconds). React-Query will automatically fetch data at this interval, and the component will re-render with the updated data. It handles loading states and errors transparently, providing a smooth user experience.