Skip to content

Instantly share code, notes, and snippets.

@jeffpamer jeffpamer/README.md
Last active Feb 18, 2016

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Feb 18, 2016

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

@johnloy

This comment has been minimized.

Copy link

commented Feb 18, 2016

Nice!

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

@jeffpamer

This comment has been minimized.

Copy link
Owner Author

commented Feb 18, 2016

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
You can’t perform that action at this time.