Skip to content

Instantly share code, notes, and snippets.

@jeffpamer
Last active February 18, 2016 16:29
Show Gist options
  • Save jeffpamer/b427a971320063715e58 to your computer and use it in GitHub Desktop.
Save jeffpamer/b427a971320063715e58 to your computer and use it in GitHub Desktop.
Reduce boilerplate using react-redux connect decorator and reselect selectors

When using the connect decorator (https://github.com/reactjs/react-redux) in conjunction with selectors (https://github.com/reactjs/reselect) a common pattern in your components appears:

import { connect } from 'react-redux';
import { selectCustomer } from 'stores/customer';
import { selectOrders, selectDeliveries } from 'stores/order';

@connect((state) => ({
    customer: selectCustomer(state),
    orders: selectCustomer(state),
    deliveries: selectDeliveries(state)
})
export default class CustomerComponent extends Component {
    constructor(props) {
        props.customer
        // [...]

A bit of this boilerplate can be short-circuited into a collection that simply lists your selectors.

import connectSelectors from 'connectSelectors';
import { selectCustomer as customer } from 'stores/customer';
import { selectOrders as orders, selectDeliveries as deliveries } from 'stores/order';

@connectSelectors({
    customer,
    orders,
    deliveries
})
export default class CustomerComponent extends Component {
    constructor(props) {
        props.customer
        // [...]
import { connect } from 'react-redux';
export default function connectSelectors(selectors = {}) {
return connect((state, props) => {
const sources = Object.keys(selectors).map(selectorKey => {
return { [selectorKey]: selectors[selectorKey](state) }
});
return Object.assign({}, ...sources)
})
}
@jeffpamer
Copy link
Author

Ha, you're totally right. I think my current Object.assign obsession blinded me to that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment