Created
February 27, 2025 12:39
-
-
Save siexp/bbd05f810facceb96ce8fb64b1e7c23b to your computer and use it in GitHub Desktop.
useEffect & api pooling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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