reselect icon indicating copy to clipboard operation
reselect copied to clipboard

Howto: Use reselect at component-level without connect

Open TN1ck opened this issue 11 years ago • 5 comments

In your docs, it is only mentioned how to use reselect at the connect-level, but this wouldn't work with some parts of our application, what we needed was some way to apply functions to the props of the components, and it was actually quite easy to do this with reselect:

I created a function to wrap components with, called select:

let React = require('react');
let _     = require('lodash');

let select = (...selectors) => {
    return (WrappedComponent) => {

        let NewWrappedComponent = React.createClass({
            render: function () {
                let appliedSelectors = selectors.map(fn => {
                    return fn(this.props);
                });
                let calculatedProps = _.merge(...appliedSelectors);
                return <WrappedComponent {...this.props} {...calculatedProps} />;

            }
        });
        return NewWrappedComponent;
    };
};

module.exports = select;

With select you can easily use selectors at Component-level:

let { createSelector } = require('reselect');
let React = require('react');

let shopItemsSelector = state => state.shop.items
let taxPercentSelector = state => state.shop.taxPercent

const subtotalSelector = createSelector(
  shopItemsSelector,
  items => items.reduce((acc, item) => acc + item.value, 0)
)

let Component = select(subTotalSelector)(React.createClass({...}));

I've just build it, so it's really simple at the moment, but it works really good for me, hot-reloading worked out of the box.

I just wanted to share, because someone might have the same use-case as I did.

TN1ck avatar Nov 17 '15 17:11 TN1ck

Thanks @TN1ck. I think to be more consistent with (state, props) it should be

let appliedSelectors = selectors.map(fn => {
  return fn(_, this.props);
})

panayi avatar Nov 23 '15 16:11 panayi

Also here is a version with ES6 classes:

import React, { Component } from 'react'
import _ from 'lodash'

const select = (...selectors) => {
  return WrappedComponent => class extends Component {
    render() {
      const appliedSelectors = selectors.map(fn => {
        return fn(_, this.props)
      })
      const calculatedProps = _.merge(...appliedSelectors)
      return (
        <WrappedComponent {...this.props} {...calculatedProps} />
      )
    }
  }
}

export default select

// Usage:
// select(avatarSelector)(AvatarComponent)

panayi avatar Nov 23 '15 16:11 panayi

@TN1ck @panayi Great, I appreciate both of you writing this up! Thanks.

@panayi Looks like you are passing lodash as the 1st param into the function getting memoized? I guess that was intended to be a placeholder. I'm not sure that I agree about (_, props) being more consistent, my initial feeling is that I would leave that function call how @TN1ck had it.

This would be a good fit for this FAQ question on the readme if anyone fancies submitting a pull request. No worries if not, I'll get around to adding it soon.

ellbee avatar Nov 23 '15 20:11 ellbee

@TN1ck Sorry, I'm not following what the purpose of this is. Do you have a more concrete example and an explanation of why you can't use reselect in the normal way?

Thanks.

mindjuice avatar Nov 25 '15 06:11 mindjuice

@TN1ck I don't understand how this code works. Won't appliedSelectors just be an array of the results of running the passed-passed in selectors? Something like: [2, 'cool val', {}]. So when you run _.merge(...appliedSelectors) you're going to get garbage out:

{ [Number: 2]
  '0': 'c',
  '1': 'o',
  '2': 'o',
  '3': 'l',
  '4': ' ',
  '5': 'v',
  '6': 'a',
  '7': 'l' }

danny-andrews avatar May 16 '17 18:05 danny-andrews