ArticleZip > Polling Api Every X Seconds With React

Polling Api Every X Seconds With React

Polling an API at regular intervals is a common scenario in web development, especially when working with real-time data or when you need to keep your application synchronized with a backend server. In this guide, we will explore how to poll an API every X seconds using React, a popular JavaScript library for building user interfaces.

When it comes to fetching data from an API periodically, we have a few options at our disposal. One approach is to use the `setInterval` method in JavaScript to repeatedly fetch data at specific intervals. However, when working with React, a more efficient way is to leverage the `useEffect` hook, which allows us to perform side effects in function components.

To begin, let's create a new React component that will handle the API polling logic. We'll start by importing `useState` and `useEffect` from the `react` package:

Jsx

import React, { useState, useEffect } from 'react';

const PollingComponent = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        const jsonData = await response.json();
        setData(jsonData);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData(); // Initial fetch

    const intervalId = setInterval(fetchData, 5000); // Poll every 5 seconds

    return () => clearInterval(intervalId); // Clean up interval on unmount
  }, []);

  return (
    <div>
      {data ? (
        <pre>{JSON.stringify(data, null, 2)}</pre>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
};

export default PollingComponent;

In this example, we define a functional component `PollingComponent` that fetches data from an API endpoint every 5 seconds. The `useEffect` hook is used to initiate the initial fetch and set up the polling mechanism using `setInterval`.

When the component mounts, the `fetchData` function is called to fetch the initial data. Subsequently, we set up an interval that calls `fetchData` every 5 seconds. It's crucial to clear the interval when the component is unmounted to prevent memory leaks.

Finally, we display the fetched data within the component. When the data is available, it is displayed in a preformatted JSON format. While the data is being fetched, a simple "Loading..." message is shown to inform the user.

By following this pattern, you can efficiently poll an API at regular intervals with React while ensuring good performance and clean resource management. Remember to adjust the polling interval (`5000` milliseconds in this case) based on your specific requirements to strike a balance between responsiveness and server load.