Last active
August 24, 2023 20:38
-
-
Save jameslockwood/6d9a7ff1ab5ac1aeb7ae6835c74ac341 to your computer and use it in GitHub Desktop.
thunk poller - easily poll redux thunk functions
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
// 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