JAVASCRIPT

Polling an API for Real-Time Updates

Implement API polling to periodically check a server for data updates, a simple strategy for near real-time data synchronization in web applications.

let pollIntervalId = null;

async function pollApiForUpdates(url, intervalMs, callback, initialData = null) {
  let currentData = initialData;

  const fetchData = async () => {
    try {
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      const newData = await response.json();

      // Compare new data with current data to avoid unnecessary updates
      if (JSON.stringify(newData) !== JSON.stringify(currentData)) {
        currentData = newData;
        callback(newData); // Notify component/application of update
      } else {
        console.log(`No new updates from ${url}`);
      }
    } catch (error) {
      console.error(`Error polling ${url}:`, error.message);
      // Potentially stop polling or implement backoff strategy here
    }
  };

  // Clear any existing interval to prevent duplicates
  if (pollIntervalId) {
    clearInterval(pollIntervalId);
  }

  // Initial fetch immediately
  await fetchData(); 
  // Set up periodic polling
  pollIntervalId = setInterval(fetchData, intervalMs);
  console.log(`Polling started for ${url} every ${intervalMs / 1000} seconds.`);

  // Return a stop function
  return () => {
    clearInterval(pollIntervalId);
    pollIntervalId = null;
    console.log(`Polling stopped for ${url}.`);
  };
}

// Example Usage:
// let stopPollingOrders;
// const handleOrderUpdate = (orders) => {
//   console.log('Orders updated:', orders);
//   // Update your UI here
// };

// // Start polling every 5 seconds for order data
// // For demonstration, using a mock API that always returns the same data
// // In a real scenario, the API would return changing data.
// pollApiForUpdates('https://jsonplaceholder.typicode.com/posts/1', 5000, handleOrderUpdate)
//   .then(stopFn => {
//     stopPollingOrders = stopFn;
//     // To stop polling after some time, e.g., 30 seconds:
//     // setTimeout(() => {
//     //   stopPollingOrders();
//     // }, 30000);
//   });
How it works: This snippet implements API polling, a technique to periodically fetch data from an API to check for updates. The `pollApiForUpdates` function takes a URL, interval, and a callback. It fetches data at the specified interval and invokes the callback only if the new data differs from the previously fetched data, preventing unnecessary state updates. It also returns a function to easily stop the polling, crucial for resource management in single-page applications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs