Skip to content

Instantly share code, notes, and snippets.

@jameslockwood
Last active August 24, 2023 20:38
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jameslockwood/6d9a7ff1ab5ac1aeb7ae6835c74ac341 to your computer and use it in GitHub Desktop.
Save jameslockwood/6d9a7ff1ab5ac1aeb7ae6835c74ac341 to your computer and use it in GitHub Desktop.
thunk poller - easily poll redux thunk functions
// createPollingAction() returns a thunk which continually polls, once invoked.
// subsequent invocations will cancel the previous poll queue.
const createPoller = (interval, initialDelay) => {
let timeoutId = null;
let poller = () => {};
return fn => {
window.clearTimeout(timeoutId);
poller = () => {
timeoutId = window.setTimeout(poller, interval);
return fn();
};
if (initialDelay) {
return timeoutId = window.setTimeout(poller, interval);
}
return poller();
};
};
export const createPollingAction = (action, interval, initialDelay) => {
const poll = createPoller(action, initialDelay);
return () => (dispatch, getState) => poll(() => action(dispatch, getState));
};
// -----------------------
// example usage - when the returned thunk is invoked, it calls the thunk every 30 seconds
const fetchAction = createPollingAction(dispatch => {
fetch('foo').then(
json => dispatch(success(json)),
e => dispatch(failure(e))
);
}, 30000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment