Blog>
Snippets

Polling an API for Updates

Create an example where useSyncExternalStore is used to poll an external API at regular intervals for the most up-to-date data.
import { useEffect, useState, useCallback } from 'react';
import { useSyncExternalStore } from 'react';

// Simulated API call to fetch data
const fetchLatestData = async () => {
  // Replace with your API endpoint
  const response = await fetch('https://api.example.com/data');
  if (!response.ok) {
    throw new Error('Network response was not ok ' + response.statusText);
  }
  return await response.json();
};

// Polling Hook
function usePolling(fetchFunction, interval) {
  const [state, setState] = useState(null);

  const getSnapshot = useCallback(() => state, [state]);
  const subscribe = useCallback((callback) => {
    const intervalId = setInterval(async () => {
      try {
        const data = await fetchFunction();
        setState(data);
        callback();
      } catch (error) {
        console.error('Failed to poll:', error);
      }
    }, interval);
    return () => clearInterval(intervalId);
  }, [fetchFunction, interval]);

  useEffect(() => {
    fetchFunction().then(setState);
    return () => {};
  }, [fetchFunction]);

  return useSyncExternalStore(subscribe, getSnapshot);
}

// Example Component
function MyComponent() {
  const data = usePolling(fetchLatestData, 5000); // Poll every 5 seconds

  return (
    <div>
      <h1>Latest Data:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}
This code defines a custom Hook `usePolling` that takes a `fetchFunction` to hit an API and an `interval` in milliseconds. It uses the React `useSyncExternalStore` hook to provide a stateful value that updates on a fixed interval. The `fetchLatestData` function simulates an API call. The `MyComponent` component demonstrates the use of `usePolling` to display the latest data by polling the API every 5 seconds.