Last active
June 12, 2023 18:45
-
-
Save crazy4groovy/ee00a7d8d53a3c9b36561a187f7bee37 to your computer and use it in GitHub Desktop.
A simple hook to implement interval polling of any thunk (ReactJS)
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
import React, { useState } from 'react'; | |
import usePolling from './usePolling'; | |
import ... | |
const useCustomPolling = () => { | |
const [state, setState] = useState() | |
const cb = async (cancelPolling) => { | |
// do some logics here... whatever... | |
if (!isDone) return; // Continue polling | |
// do some more logics here... | |
cancelPolling(); // Stop polling | |
}; | |
const cancelPolling = usePolling(cb, 5000); | |
return { state, cancelPolling }; | |
}; |
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
import { useEffect, useRef } from 'react'; | |
const usePolling = (callback, delay) => { | |
const savedCallback = useRef(); | |
const intervalRef = useRef(); | |
const cleanup = () => clearInterval(intervalRef.current); | |
useEffect(() => { | |
savedCallback.current = callback; | |
}, [callback]); | |
useEffect(() => { | |
const tick = () => savedCallback.current(cleanup); | |
if (delay != null) { | |
intervalRef.current = setInterval(tick, delay); | |
} | |
tick(); | |
return cleanup; | |
}, [delay]); | |
return cleanup; | |
}; | |
export default usePolling; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment