Last active
May 23, 2017 19:11
-
-
Save malectro/24d3a8632a69ad0ef8902e55f52ad957 to your computer and use it in GitHub Desktop.
Evolution of Sense ActionCreators
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) => { | |
// 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