Skip to content

Instantly share code, notes, and snippets.

@horaciosystem
Last active October 23, 2018 22:47
Show Gist options
  • Save horaciosystem/0e5e1002e72ac1bdc24782ab21fdf1df to your computer and use it in GitHub Desktop.
Save horaciosystem/0e5e1002e72ac1bdc24782ab21fdf1df to your computer and use it in GitHub Desktop.
import React, { Component, createContext } from "react"
import { differenceBy } from "lodash/fp"
const { Provider, Consumer: MultiSelectConsumer } = createContext({})
export function toggleItemUpdater(item) {
return ({ items: currentStateItems }) => {
const hasItem = currentStateItems.some(it => it.id === item.id)
if (hasItem) {
return { items: currentStateItems.filter(it => it.id !== item.id) }
}
return { items: [...currentStateItems, item] }
}
}
class MultiSelectProvider extends Component {
state = {
items: []
}
toggleItem = item => this.setState(toggleItemUpdater(item))
clearAll = () => this.setState({ items: [] })
addMany = list =>
this.setState(prevState => ({
items: prevState.items.concat(list)
}))
clearItems = list => {
this.setState(prevState => ({
items: differenceBy("id", prevState.items, list)
}))
}
render() {
return (
<Provider
value={{
items: this.state.items,
toggleItem: this.toggleItem,
clearItems: this.clearItems,
addMany: this.addMany,
clearAll: this.clearAll
}}
>
{this.props.children}
</Provider>
)
}
}
function withProvider(Component) {
return props => (
<MultiSelectProvider>
<Component {...props} />
</MultiSelectProvider>
)
}
export default MultiSelectProvider
export { withProvider as withMultiSelectProvider, MultiSelectConsumer }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment