Skip to content

Instantly share code, notes, and snippets.

@siexp
Created February 27, 2025 12:39
Show Gist options
  • Save siexp/bbd05f810facceb96ce8fb64b1e7c23b to your computer and use it in GitHub Desktop.
Save siexp/bbd05f810facceb96ce8fb64b1e7c23b to your computer and use it in GitHub Desktop.
useEffect & api pooling
import { useState, useEffect } from 'react';
const usePolling = (url, interval = 5000) => {
const [data, setData] = useState(null);
const [isFetching, setIsFetching] = useState(true);
useEffect(() => {
let isMounted = true;
let timerId;
const fetchData = async () => {
try {
const response = await fetch(url);
const result = await response.json();
if (isMounted) setData(result);
} catch (error) {
console.error("Error fetching data:", error);
} finally {
if (isMounted) {
timerId = setTimeout(fetchData, interval);
}
}
};
fetchData();
return () => {
isMounted = false;
clearTimeout(timerId);
};
}, [url, interval]);
return { data, isFetching };
};
export default usePolling;
useEffect(() => {
setInterval(() => {
fetch('/api/data')
.then(response => response.json())
.then(data => setData(data));
}, 5000);
}, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment