Last active
June 17, 2017 05:07
-
-
Save garretttaco/7cb6fedb6008512be2a1a5af52dc721e to your computer and use it in GitHub Desktop.
Prototype withHandlers HoC to declare updater handlers based on object keys.
This file contains 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
// 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