Support for selectors that take arguments?
The general consensus here and over at nuclear-js is that if a selector needs a dynamic argument, then that argument should probably be state in the store.
My arguments are all state in the store, but they live in different slices of state. Each slice has its own selectors that act only on that slice (as is the pattern suggested by @gaearon here), and therefore doesn't have access to the values that live in other slices. How can I create selectors that use those values without passing them as arguments?
Just to be super clear, let me illustrate with an example:
Let's say I have a reducer for "animal" entities that also has a selector for getting animal options by category (to use in an HTML select)...
state/entities/animals.js
const initialState = [
{ id: 1, name: 'Dog', category: 'Mammal' },
{ id: 2, name: 'Lion', category: 'Mammal' },
{ id: 3, name: 'Lizard', category: 'Reptile' },
// +1000 more...
];
export default (state, action) => { /* ... */ };
export const getAnimalOptionsByCategory = (state, category) =>
state.filter((animal) => animal.category === category)
.map((animal) => ({ value: animal.id, label: animal.name }));
Somewhere else I have a reducer that maintains the category selected by the user...
state/ui/animalFilter.js
const initialState = {
category: 'Mammal',
};
export default (state, action) => { /* ... */ };
export const getCategory = (state) => state.category;
Finally, the root reducer combines the animals and animalFilter reducers using Redux's combineReducers function. This is also where we locate the root-level selectors to be used in mapStateToProps functions. I'd like to add a selector here that selects the user-chosen category from the animalFilter slice, and passes it to the getAnimalOptionsByCategory selector from the animals slice so I can get all options for that category. Unfortunately, I don't seem to be able to do this with reselect...
state/rootReducer.js
import { createSelector } from 'reselect';
import { combineReducers } from 'redux';
import animals, * as fromAnimals from './entities/animals';
import animalFilter, * as fromAnimalFilter from './ui/animalFilter';
export default combineReducers({ animals, animalFilter });
export const getFilteredAnimalOptions = createSelector( /* What goes here? */ );
Structuring selectors in this way is a fairly common pattern and I'm surprised reselect doesn't cater for it. Will you be supporting this in the future?
Hey @patrick-ivers, sorry this didn't get a reply. I tried to give an example of what the problem is with selectors and arguments is over on issue #253, let me know if it doesn't makes sense.