reduxjs / reselect

Selector library for Redux

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can you pass an argument to a selector?

0x80 opened this issue · comments

I have a component that computes derived data from a store, but based on a variable argument. Can I use reselect for this?

For example I would like to move the following method to a selector. It merges the options and current values from a filter store based on the group argument:

getOptionsWithValues (group) {
    const { options, values } = this.props.filter
    const opts = options.filter(opt => opt.group === group)
    return opts.map(opt => ({ ...opt, value: values.get(opt.id) }))
  }

I feel like I should move this computation outside of the component. In a traditional Flux implementation I would create this method as a getter on the store but I don't know how to approach this with Redux.

I just realized that "group" in this case should also be part of the application state. In which case all required data will be available to the selector. Hurray \o/

That is generally my conclusion as well. See this issue for an additional take: #18

commented

I am not too sure about this, consider a search query like 'cheese' search against a shopping list, while getListItems gives you the same data, but as you search 'cheese', then 'bread', then 'cheese' again, the first and third searches won't be a cache hit as the the states representing them are different, even though they should return the same items

@niksosf I agree, IMO this isn't sufficient explanation for certain use cases. However, I'd like to push back on your example, since user input for searches have infinite possibility, which is something that you might not want to always cache.

Maybe a practical example is an Admin Dashboard where you can select a particular User and display attributes about the user as a sortable chart.

In this case, you want to be able to select the User's data (which is the parameter to the selector) and cache the calculation (sortable chart).

I found this comment by the author to create a memoized factory for your selectors:
#18 (comment)

However, in my experience so far, this is a common enough use case that I wish there were more direct support for this in reselect.

EDIT: There is also an example of memoized factories in the README FAQs:
https://github.com/reduxjs/reselect/tree/ac77610bbb0a3cab9b280ea5ea379c2387017446#q-how-do-i-create-a-selector-that-takes-an-argument