reselect icon indicating copy to clipboard operation
reselect copied to clipboard

How to pass simple argument to createSelector?

Open mistre83 opened this issue 10 years ago • 15 comments

I'm sorry for this question but i'm very new to reselect, react etc...

Its possible to pass an argument to createSelector ?

I have a selector like this:

export const getMonitorsOfType = createSelector(
    [getMonitors], (monitors) => {
        return _.get(monitors);
    }
);

getMonitors is a "simple selector" that take a part of the state:

export const getMonitors = state => state.systems.collection[0].monitors;

Dont care abut the [0], i'm just testing for semplicity :)

the getMonitorsOfType should call getMonitors and the return value should be _.get(monitors, inputValue).

For example, i've think an selector like this:

export const getMonitorsOfType = createSelector(
    [getMonitors, inputValue], (monitors, inputValue) => {
        return _.get(monitors, inputValue);
    }
);

This inputValue is just a variable that come from my components (is the routing properties: this.props.params.monitor_id).

So, in mapStateToProps i should have:

const mapStateToProps = (state) => {
    return {
        monitors: getMonitorsOfType(state, inputValue),
    }
};

Maybe i'm doing all in a totally wrong way....

mistre83 avatar Jun 20 '16 21:06 mistre83

Have you seen this question from the FAQ?

https://github.com/reactjs/reselect/blob/master/README.md#q-how-do-i-create-a-selector-that-takes-an-argument

ellbee avatar Jun 21 '16 06:06 ellbee

Oh sorry, i didnt see this :(

Instead of create a selector that take an arguments, will be better to create a "pure" selector that give me the monitor export const getMonitors = state => state.systems.collection[0].monitors; and inside the component i will call the _.get ?

In this way, i dont have to create a factory and i can move the logic inside my component.

Maybe in the future, if i will need this functionality elsewhere, i can move this as factory.

mistre83 avatar Jun 21 '16 07:06 mistre83

If inputValue is taken from props maybe you could do something like this:

export const getMonitorsOfType = createSelector(
    getMonitors,
    (_, props) => props.params.monitor_id,
    (monitors, inputValue) => {
        return _.get(monitors, inputValue);
    }
);

https://github.com/reactjs/reselect#accessing-react-props-in-selectors

ellbee avatar Jun 21 '16 20:06 ellbee

Is so simple: let's give you an example, I have a mapStateToProps like this:

function mapStateToProps(state) {
  return {
    categoryHistory: getCategoryHistory(state,'extended')
  }
}

then I've create a selector like this:

export const getCategoryHistory = (state, type) => createSelector([getTaxonomy, selectedCategoryID], (categories, categoryID) => categories.getIn([type, categoryID]) || [])(state)

The solution is to call createSelector() passing the state as parameters:

createSelector()(state)

inside the selector you can use all the parameter you want to pass through.

ttessarolo avatar Nov 30 '17 16:11 ttessarolo

@ttessarolo

export const getCategoryHistory = (state, type) => createSelector(...)(state)

I fear since getCategoryHistory creates a new selector at each call, memoization won't work as expected.

tkrugg avatar Feb 19 '18 15:02 tkrugg

@ttessarolo, @tkrugg

Curried selectors that accept arguments can retain their memoization if created in a mapStateToProps that returns a function.

const makeGetC = (a, b) => createSelector(...)

const mapStateToProps = (state, ownProps) => {
  const { a, b } = ownProps;
  const getC = makeGetC(a, b);
  
  return (state, ownProps) => ({
    c: getC(state)
  });
}

brietsparks avatar Apr 11 '18 18:04 brietsparks

@brietsparks

you’re right. really smart.

Now we just need a factory function that do all the job of creating a selector returning a function...

ttessarolo avatar Apr 11 '18 18:04 ttessarolo

...or just:

export const getCategoryHistory = (state, type) => (state, type) => createSelector(...)(state)

ttessarolo avatar Apr 11 '18 18:04 ttessarolo

@brietsparks what does the selector look like in this case?

adriaanbalt avatar Dec 08 '18 22:12 adriaanbalt

@brietsparks Won't it create a a new memoized-context every single time the function makeGetC is called? if so, i can see point of memoization starts to fade.

isaadabbasi avatar Jul 29 '19 21:07 isaadabbasi

@brietsparks

Curried selectors that accept arguments can retain their memoization if created in a mapStateToProps that returns a function.

const makeGetC = (a, b) => createSelector(...)

const mapStateToProps = (state, ownProps) => {
  const { a, b } = ownProps;
  const getC = makeGetC(a, b);
  
  return (state, ownProps) => ({
    c: getC(state)
  });
}

Is this going to memoize if the a/b props change with time? Don't think so?

Tomassito avatar Nov 24 '20 16:11 Tomassito

Here is an example of how to pass a dynamic argument to createSelector.

example of the redux state:

{
    articlesState: {
        'a1': {
            title: 'article title 1',
            ...
        },
        'a2': {
            title: 'article title 1',
            ...
        }
    },
    commentsState: {
        ...
    },
    ...
}

Selector code:


// pick articles state from the main redux state
const selectArticlesState = state => state.articlesState;

// memoize articles map if needed
const selectArticlesMap = createSelector(
    [selectArticlesState],
    value => value || {}
);

// Create a select function to get the dynamic arg value e.g: articleId
export const selectArticleId = (state, articleId) => articleId;


// This selector will return Article data base on articleId as dynamic arg.
export const selectArticleById = createSelector(
    [
        selectArticlesMap, // get the articles map data from the state.
        selectArticleId, // get the dynamic arg.
        // you can add more select functions state/dynamic arg.
    ],
    (
        articlesMap, // the articles map object value
        articleId // the article id value
    ) => articlesMap[articleId]
);

Container code:

...
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import {
    selectArticleById,
} from '../../selectors';
...

class ArticleContainer extends React.Component {
    ...
}

ArticleContainer.propTypes = {
    articleId: PropTypes.string.isRequired
};

function mapStateToProps(state, ownProps) {
    // reading ArticleContainer articleId prop, this is dynamic value.
    const { articleId } = ownProps;

    return {
        // select article data by passing articleId dynamic value to the selector. 
        article: selectArticleById(state, articleId),
        ...
    };
}


export default connect(
    mapStateToProps,
    ...
)(ArticleContainer);

Hope this help.

shadiabuhilal avatar Jan 15 '21 20:01 shadiabuhilal

@shadiabuhilal is the selector memoized in the above example? I'm a beginner with reselect. Somebody above said that:

Curried selectors that accept arguments can retain their memoization if created in a mapStateToProps that returns a function.

But in this case, mapStateToProps returns an object. Does that still apply? Thanks!

popadi avatar May 18 '21 16:05 popadi

Works but breaks Typescript Screenshot 2023-04-28 at 11 10 20 AM

Without:

Screenshot 2023-04-28 at 11 10 06 AM

Turns every selector in the file into 'any'

Edit:

Fixed by extracting out:

Screenshot 2023-04-28 at 1 28 10 PM

dominictobias avatar Apr 28 '23 10:04 dominictobias

@DominicTobias : yes, you must provide TS types for every argument in the input functions. As of 4.1.x, createSelector's TS types work by inspecting the types of the input functions and their arguments. If you provide an input function that doesn't have types, that inference will break.

That would work fine inline as long as you have the types.

markerikson avatar Apr 28 '23 14:04 markerikson