Last active
September 23, 2017 03:11
-
-
Save joedski/d38494cb30783c579319d4af7ae81dda to your computer and use it in GitHub Desktop.
hof thunks: mapping resolutions
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 | |
// ... other decorators and such. | |
export function mapResolution(mapResFn) { | |
return (createThunk) => (params, meta) => async (dispatch, getState) => { | |
const res = await dispatch(createThunk(params, meta)); | |
if (res.error) return res; | |
return { | |
...res, | |
result: mapResFn(res.result, 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 }), | |
// Now we can clean up the resolution from the related endpoint. | |
thunk.mapResolution((relatedRes) => cleanUpRelatedRes(relatedRes)) | |
)(myRelatedEndpoint) | |
: thunk.resolvingWith(() => res) | |
)) | |
)(myEndpoint), | |
}) | |
) | |
)(class MyResourceDisplay extends PureComponent { | |
// same old, same old... | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment