Skip to content

Instantly share code, notes, and snippets.

@jtulk
Created July 13, 2017 06:44
Show Gist options
  • Save jtulk/f400aec7f9a2abaa654d72e06de3b0c2 to your computer and use it in GitHub Desktop.
Save jtulk/f400aec7f9a2abaa654d72e06de3b0c2 to your computer and use it in GitHub Desktop.
import { startFetch, abortFetch, errorFetch, updateFetch } from './syncActionCreators';
// Run the async fetch if the data is stale, otherwise abort the fetch and log it
export const updateDemoContentAsync = () => {
// Redux Thunk allows this, see its docs for more detail
return (dispatch, getState) => {
// Get the state of the store synchronously for the REDUCER IN QUESTION, e.g. myContent here
const timeSinceLastFetch = getState().myContent.lastFetched;
// perform the async call if the data is older than the allowed limit
const isDataStale = Date.now() - timeSinceLastFetch > timeToStale;
if (isDataStale) {
dispatch(startFetch());
// Run the async fetch
myApi.fetchData()
.then(content => {
dispatch(updateFetch(content));
})
.catch(err => {
dispatch(errorFetch(err));
});
} else {
dispatch(abortFetch());
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment