Skip to content

Instantly share code, notes, and snippets.

@garretttaco
Last active June 17, 2017 05:07
Show Gist options
  • Save garretttaco/7cb6fedb6008512be2a1a5af52dc721e to your computer and use it in GitHub Desktop.
Save garretttaco/7cb6fedb6008512be2a1a5af52dc721e to your computer and use it in GitHub Desktop.
Prototype withHandlers HoC to declare updater handlers based on object keys.
// Definition - withPropertyHandlers.js
import { compose, withHandlers } from 'recompose'
function upperCaseFirstCharacter(str) {
return `${str.charAt(0).toUpperCase()}${str.slice(1)}`
}
export default function withPropertyHandlers(
properties,
updaterName,
updater,
handlersPrefix = 'update',
) {
const keyHandlers = properties.reduce((handlers, property) => {
return {
...handlers,
[`${handlersPrefix}${upperCaseFirstCharacter(property)}`]: props =>
props[updaterName](property),
}
}, {})
return compose(
withHandlers({
[updaterName]: updater,
}),
withHandlers(keyHandlers),
)
}
// Implementation - form.js
const enhance = withPropertyHandlers(
['test', 'test2'],
'updater',
({ optinForm, updateOptinForm }) => name => value => {
updateOptinForm({
...optinForm,
[name]: value,
})
})
// Generated sub handler used
const Component = enhance(({ updateTest, updateTest2 }) => null)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment