Felix
Felix

Reputation: 4595

NgRx selector when feature slice is null

In my application there is a store with a feature slice:

@NgModule({
    imports: [
    CommonModule,
    TranslateModule.forChild({}),
    StoreModule.forFeature('slice', slice)
    ...
})

Reducer Map for feature:

export const slice: ActionReducerMap<SliceState> = {
    someReducer
};

And feature selectors:

export const selectSliceModule = createFeatureSelector<SliceState>('slice');
export const selectItem = createSelector(selectSliceModule,
(state: SliceState) => state.someReducer.paramA);

There is a Logout action which after logout clears main store and also slice so after logout slice === null.

Component which is subscribed to feature store slice using selector selectItem then fails, because state.someReducer is null: state.someReducer.paramA.

My question is: Is it OK to use ternary operator in a selector in such case? Does it break the selector memoization? Or is there a better way to handle this situation?

// Is it OK to have ternary operator in selector?
export const selectItem = createSelector(selectSliceModule,
(state: SliceState) => state.someReducer ? state.someReducer.paramA : null);

Upvotes: 5

Views: 2047

Answers (2)

MCMatan
MCMatan

Reputation: 8863

I know this question is old, but maybe this can help someone.

Faced the same issue, it was because my component tried to access data after it was destroyed.

Adding takeUntil solved my issue

this.restaurantData$ = this.restaurantQuery$
      .pipe(
        takeUntil(this._ngOnDestroy), // Added this line
        filter((restaurantQuery) => !!restaurantQuery),
        switchMap((restaurantQuery) => restaurantQuery.valueChanges),
        map((response) => response.data.vendor)
      ); 

Now after logout, component stops listening to the selector.

Upvotes: 0

etovian
etovian

Reputation: 23

I was experiencing this problem and then realized that my reducer for the affected part of the state had no default case in its switch statement that returned the state passed to the reducer function. Without that default case, the initial state returned by the reducer is undefined. Adding the default state fixed the issue for me. Hope this helps you as well.

Upvotes: 1

Related Questions