Skip to content

Instantly share code, notes, and snippets.

@thebiltheory
Created February 12, 2020 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebiltheory/b386e0d759205956d864c8fc89a42ad9 to your computer and use it in GitHub Desktop.
Save thebiltheory/b386e0d759205956d864c8fc89a42ad9 to your computer and use it in GitHub Desktop.
Dispatch a redux action every (n) seconds
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