Search code examples
javascriptreactjsreduxreselect

Conditionally composing a selector using reselect


export const mySelector = createSelector(
    [selectorA, selectorB], // but I want selectorB or selectorC to be chosen here using logic
    (foo, bar) => {
        // ...
    }
);

I want to conditionally use selectorB or selectorC when creating this selector based on the state in the store (i.e. the value returned by another selector).

How can I do this?


Solution

  • Just to point out that the approach suggested in the accepted answer would evaluate both selectorB and selectorC on each selectorCorB call. Which is not probably the desired behaviour.

    An actual conditional call might be implemented like this:

    export const selectorCorB = createSelector(
        selectorStateX
        (...arguments) => arguments,
        (x, arguments) => x ? selectorB(...arguments) : selectorC(...arguments)
    );