Skip to content

Instantly share code, notes, and snippets.

@jeffpamer
Last active February 18, 2016 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

At the moment this won't allow for passing additional params into the selectors, unless reselect supports partial application.

@johnloy
Copy link

johnloy commented Feb 18, 2016

Nice!

Is the Object.assign bit necessary? Couldn't you just use reduce instead of map?

@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