Skip to content

Instantly share code, notes, and snippets.

@James-E-Adams
Created October 22, 2018 20:49
Show Gist options
  • Save James-E-Adams/acfd6cf6aa13fb44694e5c532c0f78ce to your computer and use it in GitHub Desktop.
Save James-E-Adams/acfd6cf6aa13fb44694e5c532c0f78ce to your computer and use it in GitHub Desktop.
Functional React Article Snippet #4
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