Last active
July 13, 2017 19:47
-
-
Save thevangelist/c64ec292b5cf7a87099de7520ff7b1f4 to your computer and use it in GitHub Desktop.
Redux Tree Query HOC with Fallback Values
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
import { connect } from 'react-redux'; | |
import _ from 'lodash'; | |
function reduxConnected(reduxTreeQuery, fallbackValue, propName) { | |
return connect(state => ({ | |
[propName]: _.get(state, reduxTreeQuery, fallbackValue) | |
})); | |
} | |
export default reduxConnected; | |
... | |
// Compose for great good! | |
const addFooAndBar = _.compose( | |
reduxConnected("data.foo", "?", "foo"), | |
reduxConnected("data.bar", "?", "bar") | |
); | |
var FooBar = props => <span>{props.foo} {props.bar}</span>; | |
FooBar = addFooAndBar(FooBar); | |
// Manual without compose | |
FooBar = reduxConnected("data.foo", "?", "foo")(FooBar); | |
FooBar = reduxConnected("data.bar", "?", "bar")(FooBar); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for @epeli for reducing the boilerplate and standardizing the HOC.