Why does the second argument to selector have to be props?
I was trying to figure out the best way to pass a runtime argument to a selector and I have two points of confusion about the proposed approach in the faq: https://github.com/reactjs/reselect#accessing-react-props-in-selectors
- Why does the second argument have to be props? Using props ties the selector to a specific component while allowing passing of any arbitrary argument seems more flexible so not sure why it would be a bad idea to just to pass your runtime argument (entityId for example).
- Should the sample code be calling the mapStateToPropsFactory like shown below? Otherwise I'm confused as to how this would work.
import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../components/TodoList'
import { makeGetVisibleTodos } from '../selectors'
const makeMapStateToProps = () => {
const getVisibleTodos = makeGetVisibleTodos()
const mapStateToProps = (state, props) => {
return {
todos: getVisibleTodos(state, props)
}
}
return mapStateToProps
}
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
const VisibleTodoList = connect(
makeMapStateToProps(), // <=== Shouldn't we be calling the factory function here?
mapDispatchToProps
)(TodoList)
export default VisibleTodoList
The second argument does not "have" to be props. You can pass any number of additional arguments to a selector. However, those arguments are passed to every "input selector". Here's a rough simplified sketch of what createSelector does:
function createSelector(inputSelectors, outputSelector) {
return function(...selectorArgs) {
const inputs = inputSelectors.map( inputSelector => inputSelector(...selectorArgs) );
return outputSelector(...inputs);
}
}
So, if one input selector expects arguments like (state, {someField}), and another expects (state, someNumber, anotherNumber), using those together will be a problem.
As for passing in props as an argument, that also doesn't "tie the selector to a specific component". It merely means that props should match the parameters expected by the input selectors.
Finally, the React-Redux connect() function will do a test call of the provided mapState function when the component is created. If mapState returns another function instead of an object, it assumes that the initial mapState function was a factory, and uses the returned function as the real mapState instead. So, you want to pass in a reference to the factory function. If you call the factory function yourself, you've gone back to creating a single function that is shared across all instances of the component.
Thanks Mark.
so then why isn't it a good idea to have a selector like this where the caller always passes in the state and the user id?
const getTodos = state => state.todos
const getIdToFetch = (state, id) => id
const getTodosBy = createSelectors(getTodos, getIdToFetch,
(todos, userId) => todos.filter(todo => todo.userId === userId)
);
Uh... why wouldn't it be a good idea? Pretty sure I've written that sort of thing myself.
Maybe I'm getting confused but the documentation seems to imply it's not a viable approach.
Q: How do I create a selector that takes an argument?
A: Keep in mind that selectors can access React props, so if your arguments are (or can be made available as) React props, you can use that functionality. See here for details.
Otherwise, Reselect doesn't have built-in support for creating selectors that accepts arguments, but here are some suggestions for implementing similar functionality...
source: https://github.com/reactjs/reselect/blob/master/README.md#q-how-do-i-create-a-selector-that-takes-an-argument
I've always had the impression the docs kind of overstate that idea, to be honest.
OK, thanks Mark. I was confused as to what the concern with the approach above but it sounds like it's a good approach.
Hi @markerikson, could you please clarify a bit further, because I've asked a similar question here and received no response.
Given that a real-world Redux app is going to be broken down into multiple slices, each with their own localized selectors, doesn't it make sense to be able to pass in extra arguments so they can access other parts of state?
Top-level selectors (used by components) can still accept just the state object, but it makes it hard to compose top-level selectors when input selectors can only accept the state object. Or am I missing something obvious? 😛
Another way to put it is: How do I use reselect with @gaearon's suggested approach to selectors?
@patrick-ivers : Erm... well, per my comments earlier in the thread, I've never really understood why the Reselect docs and issues say you "can't / shouldn't pass in arguments to selectors". You absolutely can , within the limitations described earlier (all "input selectors" are given the same arguments).
As for questions about encapsulation and reuse and whatnot, to a large extent that seems like it's about what limitations you want to impose on yourself in terms of app structure. I personally haven't tried to use Dan's approach of "exposing selectors upwards".
To be honest, I don't have a lot of really specific advice to offer here, other than "do what works for you" :) That said, I can tell you that my React/Redux links list does have a bunch of articles about use of selectors and some ways to "encapsulate" them. See the Redux Techniques#Selectors and Normalization and Redux Architecture#Encapsulation sections for those articles. In particular, check out Randy Coulman's articles about encapsulating and globalizing selectors, and a couple articles on other blogs in response to that topic about scoping selectors and globalizing selectors.
const getTodos = state => state.todos
const getIdToFetch = (state, id) => id
const getTodosBy = createSelectors(getTodos, getIdToFetch,
(todos, userId) => todos.filter(todo => todo.userId === userId)
);
If you have 2 different Todo Lists on a page then getTodosBy won't memoize because it is called with a different id on each state change, which invalidates the cache (the cache only has a single item).
Sure, but in that case you use the "factory function" syntax for defining a mapState function, and create a unique selector instance per component instance so things memoize correctly.
I kinda feel like the "don't use arguments for selectors" advice is along the same lines as Dan's SO comment about "don't use getState in thunks". Sure, there's some valid concerns to be aware of, but the advice is stated too broadly and is discouraging people from doing something that actually helps them solve the problems they're dealing with.
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 won't that create a new selector on each call preventing memoization?
Yes is indeed useless to use selectors with params...
Actually it's not useless to use selectors with params. It's just the approach your using that makes them useless.
Thanks! Could you please provide a correct counter example of my code?
Sure, look at my code above.