Last active
September 23, 2017 01:57
-
-
Save joedski/765895d9a709d00b0c18d1b91c0319d1 to your computer and use it in GitHub Desktop.
hof thunks: first decorator
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 | |
// Used to dispatch the thunk. | |
// Rather boring compared to the rest. | |
export function map(fn) { | |
return (createThunk) => (params, meta) => fn(createThunk(params, meta)); | |
} | |
// These params are enforced. | |
export function withParams(overrideParams) { | |
return (createThunk) => (params, meta) => createThunk( | |
{ ...params, ...overrideParams }, | |
meta | |
); | |
} | |
// These params are overridable. | |
export function defaultParams(params) { | |
return (createThunk) => (overrideParams, meta) => createThunk( | |
{ ...params, ...overrideParams }, | |
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', | |
}) | |
)(myEndpoint), | |
}) | |
) | |
)(class MyResourceDisplay extends PureComponent { | |
handleClick(event) { | |
event.preventDefault(); | |
const { result, error } = | |
await this.props.getMyResource({ | |
name: 'foo', | |
order: 'asc', | |
}); | |
if (error) { | |
this.setState({ | |
status: 'error', | |
lastError: error, | |
// not clearing result. | |
}); | |
} | |
else { | |
this.setState({ | |
status: 'success', | |
hasReceivedBefore: true, | |
lastError: null, | |
result, | |
}); | |
} | |
} | |
// ... other componenty stuff here. | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment