reduxjs / reselect

Selector library for Redux
MIT License
19.04k stars 670 forks source link

call multiple selectors with params #597

Closed inikonorov closed 1 year ago

inikonorov commented 1 year ago

I have the selector:

const selectAnything = createSelector(
  [
     // ... any selectors,
    (state, anyVar) => anyVar,
  ],
  (substate, anyVar) => (...),
);

This selector I can call in component:

const anything = useSelector(state => selectAnything(state, 'ok'));

How can I call this selector in other selectors?

const selectAnything2 = createSelector(
  [
    selectAnything // ???
  ],
  (substate) => {...}
);

Can I call this selector that way?

const anything2 = useSelector(selectAnything);
markerikson commented 1 year ago

createSelector always forwards all arguments to all input selectors.

If I have:

const firstInput = (a, b, c) => a;
const secondInput = (a, b, c) => b;

const finalSelector = createSelector(
  firstInput,
  secondInput,
  (a, b) => a + b
)

then when I call finalSelector(1, 2, 3), it will call firstInput(1, 2, 3) and `secondInput(1, 2, 3).

But no, your example of useSelector(selectAnything) will not work, because it needs two arguments, and useSelector only passes in one argument: state.

This is more obvious if you use TypeScript, which will show you exactly how many arguments the final selector requires.