Created
November 15, 2019 04:15
-
-
Save trevorglick/a74e99baa875237c5f3e42c679dc7b22 to your computer and use it in GitHub Desktop.
setInterval inside a useEffect for polling data
This file contains 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
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