Skip to content

Commit

Permalink
fix(component-store): fix memoization not working when passing select…
Browse files Browse the repository at this point in the history
…ors directly to select

This makes selectors created with `createSelector` usable with `ComponentStore.select`
which looks like it should work, but would previously result in the selector getting recomputed each time.

When select method is called with a single argument, the projector function was being passed directly to `map`,
which invokes its callback with an extra `index` argument. Because the value of index is always different,
the memoized selector would get invalidated even if the actual state remained exactly the same.
  • Loading branch information
P4 committed Mar 25, 2022
1 parent 44076f7 commit 81241af
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
18 changes: 18 additions & 0 deletions modules/component-store/spec/component-store.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
delay,
concatMap,
} from 'rxjs/operators';
import { createSelector } from '@ngrx/store';

describe('Component Store', () => {
describe('initialization', () => {
Expand Down Expand Up @@ -895,6 +896,23 @@ describe('Component Store', () => {

componentStore.ngOnDestroy();
});

it('supports memoization with createSelector', () => {
const projectorCallback = jest.fn((str: string) => str);
const memoizedSelector = createSelector(
(s: State) => s.value,
projectorCallback
);
const selector = componentStore.select(memoizedSelector);

// first call to memoizedSelector
const subscription = selector.subscribe();
// second call to memoizedSelector with the same value
componentStore.setState(INIT_STATE);

subscription.unsubscribe();
expect(projectorCallback).toHaveBeenCalledTimes(1);
});
});

describe('selector with debounce', () => {
Expand Down
2 changes: 1 addition & 1 deletion modules/component-store/src/component-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ export class ComponentStore<T extends object> implements OnDestroy {
if (observables.length === 0) {
observable$ = this.stateSubject$.pipe(
config.debounce ? debounceSync() : (source$) => source$,
map(projector)
map((arg) => projector(arg))
);
} else {
// If there are multiple arguments, then we're aggregating selectors, so we need
Expand Down

0 comments on commit 81241af

Please sign in to comment.