reselect icon indicating copy to clipboard operation
reselect copied to clipboard

Composing two selectors does not work?

Open cveld opened this issue 11 years ago • 3 comments

I have the following two selectors:

export const matchingRegionsSelector = reselect.createSelector(
  [authorizedRegionsSelector, state => state.regions.regionMap, state => state.regions.filter],
  (regionIds, regionMap: RegionMap, filter: string) => filter
    ? _.filter(regionIds, (rId:string) => regionMatches(regionMap[rId], filter))
    : regionIds);
export const visibleRegionsSelector = reselect.createSelector(
    [matchingRegionsSelector, state => state.regions.regionMap],
    (matchingRegionIds, regionMap) => {
        let visibleRegionIds = [];
        _.forEach(matchingRegionIds, id => addHierarchy(id, regionMap, visibleRegionIds));
        return visibleRegionIds;
    });

Unfortunately it appears that only matchingRegionsSelector is re-evaluated when filter changes. And even though the result of matchingRegionsSelector changes, visibleRegionsSelector is not re-evaluated.

I had to add the filter property to get it working:

export const visibleRegionsSelector = reselect.createSelector(
    [matchingRegionsSelector, state => state.regions.regionMap, state => state.regions.filter],
    (matchingRegionIds, regionMap, filter) => {
        let visibleRegionIds = [];
        _.forEach(matchingRegionIds, id => addHierarchy(id, regionMap, visibleRegionIds));
        return visibleRegionIds;
    });

Any thoughts?

cveld avatar Oct 17 '15 22:10 cveld

Hmm, I think that should work. I couldn't run the code above as there are a bunch of bits missing, but the following simplified version works as I would expect:

let state = {
  regionMap: 'abc',
  filter: 'def'
}

const matchingRegionsSelector = createSelector(
  state => state.regionMap,
  state => state.filter,
  (regionMap, filter) => {
    console.log('recalc matchingRegionsSelector');
    return regionMap + filter;
  }
);

const visibleRegionsSelector = createSelector(
  matchingRegionsSelector,
  state => state.regionMap,
  (matchingRegionIds, regionMap) => {
    console.log('recalc visibleRegionsSelector');
    return 'finished';
  }
);

console.log(1);
console.log(visibleRegionsSelector(state));
console.log(2);
console.log(visibleRegionsSelector(state));
state.filter = 'xyz';
console.log(3);
console.log(visibleRegionsSelector(state));

Can you provide me with a failing test case that I can run?

ellbee avatar Oct 18 '15 10:10 ellbee

OK I just tested again, now it is working. Apparently a sync issue between Visual Studio and Webpack! Thanks for testing with me here.

cveld avatar Oct 19 '15 19:10 cveld

No problem, glad you got it working!

ellbee avatar Oct 19 '15 19:10 ellbee