Last active
September 23, 2017 02:34
-
-
Save joedski/f2cf73c1473630810d49b2b0d5d2d929 to your computer and use it in GitHub Desktop.
hof thunks: chaining
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
// my-app/api/thunk-utils.js | |
// ... previous decorators. | |
export function then(mapResToCreateNextThunk) { | |
return (createThunk) => (params, meta) => async (dispatch, getState) => { | |
const res = await dispatch(createThunk(params, meta)); | |
if (res.error) return res; | |
return dispatch(mapResToCreateNextThunk(res, getState())(params, meta)); | |
}; | |
} | |
// NOTE: A utility thunk _creator_, not a decorator! | |
export function resolvingWith(mapArgs) { | |
return (params, meta) => (dispatch, getState) => mapArgs(getState(), params, meta); | |
} |
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
import { myEndpoint } from 'my-app/api/thunks'; | |
import * as thunk from 'my-app/api/thunk-utils'; | |
// ... other sundry imports. | |
export default compose( | |
connect( | |
null, | |
(dispatch, ownProps) => ({ | |
getMyResource: compose( | |
thunk.map(dispatch), | |
thunk.withParams({ | |
name: ownProps.name, | |
order: 'asc', | |
}), | |
thunk.then((res, state) => ( | |
resHasRelated(res) | |
? compose( | |
thunk.withParams({ relatedId: res.relatedId }) | |
)(myRelatedEndpoint) | |
: thunk.resolvingWith(() => res) | |
)) | |
)(myEndpoint), | |
}) | |
) | |
)(class MyResourceDisplay extends PureComponent { | |
// usual... | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment