Last active
May 18, 2017 18:33
-
-
Save malectro/c217bd58c98501e3358a15466f042eb0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const getUser = (userId) => (dispatch, getState) => { | |
// create a unique key for this request | |
const key = `@@getUser:${userId}`; | |
// if the action creator has already fired off a request, return it | |
const fetching = getState().fetching[key]; | |
if (fetching) { | |
return fetching; | |
} | |
// check if the request is cached | |
const cacheItem = getState().cache[key]; | |
if (cacheItem && cacheItem.expireTime > Date.now()) { | |
return; | |
} | |
const promise = api.get(`/user/${userId}`).then(user => { | |
// populate the store with the received data | |
dispatch(receiveUser(user)); | |
// set the request as cached | |
dispatch(setCache(key)); | |
// let components know we finished fetching | |
dispatch(stopFetching(key)); | |
}, () => { | |
dispatch(stopFetching(key)); | |
}); | |
// let components know we are fetching this data | |
dispatch(startFetching(key, promise)); | |
return promise; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment