Created
July 13, 2017 06:44
-
-
Save jtulk/f400aec7f9a2abaa654d72e06de3b0c2 to your computer and use it in GitHub Desktop.
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
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