Skip to content

Instantly share code, notes, and snippets.

@malectro
Last active May 23, 2017 19:11
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/24d3a8632a69ad0ef8902e55f52ad957 to your computer and use it in GitHub Desktop.
Save malectro/24d3a8632a69ad0ef8902e55f52ad957 to your computer and use it in GitHub Desktop.
Evolution of Sense ActionCreators
const getUser = (userId) => (dispatch, getState) => {
// check if we are currently fetching and return that promise
const fetching = getState().fetching[userId];
if (fetching) {
return fetching;
}
// check if the user is cached
const cacheItem = getState().cache[userId];
if (cacheItem && cacheItem.expireTime > Date.now()) {
return;
}
// initiate the request
const promise = api.get(`/user/${userId}`).then(user => {
// populate the store with the received data
dispatch(receiveUser(user));
// tell components that we have stopped fetching
dispatch(stopFetchingUser(userId, promise));
}, () => {
// do the same for the error case
dispatch(stopFetchingUser(userId, promise));
});
// let components know we are fetching this data
dispatch(startFetchingUser(userId, promise));
return promise;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment