Skip to content

Instantly share code, notes, and snippets.

@malectro
Last active May 18, 2017 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malectro/c217bd58c98501e3358a15466f042eb0 to your computer and use it in GitHub Desktop.
Save malectro/c217bd58c98501e3358a15466f042eb0 to your computer and use it in GitHub Desktop.
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