Skip to content

Instantly share code, notes, and snippets.

@joedski
Last active September 23, 2017 03:11
Show Gist options
  • Save joedski/d38494cb30783c579319d4af7ae81dda to your computer and use it in GitHub Desktop.
Save joedski/d38494cb30783c579319d4af7ae81dda to your computer and use it in GitHub Desktop.
hof thunks: mapping resolutions
// 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),
};
};
}
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