Created
February 12, 2020 12:23
-
-
Save thebiltheory/b386e0d759205956d864c8fc89a42ad9 to your computer and use it in GitHub Desktop.
Dispatch a redux action every (n) seconds
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'; | |
import { useDispatch } from 'react-redux'; | |
function useReduxPolling(action: any, interval = 2000): void { | |
const dispatch = useDispatch(); | |
const callback = useRef(action); | |
useEffect(() => { | |
callback.current = action; | |
}, [action]); | |
useEffect(() => { | |
const polling = setInterval(() => { | |
if (callback.current && typeof callback.current === 'function') { | |
dispatch(callback.current); | |
} else { | |
throw new Error('Callback must be a function'); | |
} | |
}, interval); | |
return (): void => { | |
clearInterval(polling); | |
}; | |
}, [dispatch]); | |
} | |
export default useReduxPolling; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment