Skip to content

Instantly share code, notes, and snippets.

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