Skip to content

Instantly share code, notes, and snippets.

@trevorglick
Created November 15, 2019 04:15
Show Gist options
  • Save trevorglick/a74e99baa875237c5f3e42c679dc7b22 to your computer and use it in GitHub Desktop.
Save trevorglick/a74e99baa875237c5f3e42c679dc7b22 to your computer and use it in GitHub Desktop.
setInterval inside a useEffect for polling data
const [{ data, isLoading, isError }] = useFetchData("http://localhost:3004/", {
status: "not-started"
});
const [status, setStatus] = useState<string>(data.status);
const intervalRef = useRef<number>(0);
const fetchData = async () => {
const result = await axios("http://localhost:3004/");
setStatus(result.data.status);
};
useEffect(
() => {
clearInterval(intervalRef.current);
if (status === "change-complete") return;
if (status !== "not-started") {
const interval = window.setInterval(() => {
intervalRef.current = interval;
fetchData();
}, 1000);
}
},
[status]
);
const initiateStatusCheck = () => {
fetchData();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment