Skip to content

Instantly share code, notes, and snippets.

@Revolucent
Created January 5, 2019 20:56
Show Gist options
  • Save Revolucent/51777d621fdc2b16339394856102f495 to your computer and use it in GitHub Desktop.
Save Revolucent/51777d621fdc2b16339394856102f495 to your computer and use it in GitHub Desktop.
mapDispatchToProps
import parse from 'obj-parse'
/*
In its simplest usage, mapStateToProps('foo', 'bar')
maps the state keys 'foo' and 'bar' to keys of the same
name in the props.
To alias, use an object literal: mapStateToProps('foo', {baz: 'bar.buzz'}).
In this case, we're mapping state that's more deeply nested to the 'baz' prop.
The parse method of obj-parse takes care of this for us.
Lastly, we can also use a function to do some further manipulations:
mapStateToProps('foo', {baz: state => modify(state.bar.buzz), bing: 'bong.boo'})
*/
function mapStateToProps(...names) {
return state => {
let props = {}
for (const name of names) {
if (typeof name == 'object') {
const obj = name
for (const prop in obj) {
const value = obj[prop]
if (typeof value == 'function') {
props[prop] = value(state)
} else {
props[prop] = parse(value)(state)
}
}
} else {
props[name] = state[name]
}
}
return props
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment