Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.