Created
October 22, 2018 20:49
-
-
Save James-E-Adams/acfd6cf6aa13fb44694e5c532c0f78ce to your computer and use it in GitHub Desktop.
Functional React Article Snippet #4
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 withState from 'recompose/withState' | |
import compose from 'recompose/compose' | |
import withHandlers from 'recompose/withHandlers' | |
import stringCapitalize from 'somewhere' | |
const addToSetFactory = (stateName, stateUpdaterName) => props => item => | |
props[stateUpdaterName](new Set(props[stateName]).add(item)) | |
const removeFromSetFactory = (stateName, stateUpdaterName) => props => item => | |
props[stateName].delete(item) && | |
props[stateUpdaterName](new Set(props[stateName])) | |
const defaultInitialState = () => new Set() | |
/** | |
* Puts a field in the state named stateName, and provides addToStateName | |
* and removeFromStateName methods to add/remove from the set. | |
* | |
* eg: stateName=selectedTags, stateUpdaterName=setSelectedTags | |
* | |
* The following props will get added: | |
* | |
* selectedTags, setSelectedTags, addToSelectedTags, removeFromSelectedTags | |
* | |
*/ | |
export default (stateName, stateUpdaterName, initialState) => | |
compose( | |
withState(stateName, stateUpdaterName, initialState || defaultInitialState), | |
withHandlers({ | |
['addTo' + stringCapitalize(stateName)]: addToSetFactory( | |
stateName, | |
stateUpdaterName | |
), | |
['removeFrom' + stringCapitalize(stateName)]: removeFromSetFactory( | |
stateName, | |
stateUpdaterName | |
), | |
}) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment