Search code examples
javascriptangulartypescriptngrxngrx-store

Date subscription get triggered when other part of the state change in ngrx


I have a start and end property which stores a date in my state.Anytime other part of the state get changed my subscription for start and end date get triggered.

this is my subscription

this.subs.sink = this.store
      .select(fromTransactionReducer.selectStartAndEndDate)
      .subscribe((date) => {
        console.log("range", date);
        this.range.setValue({
          start: date.start,
          end: date.end,
        });
      });

this is the selector

export const selectStartAndEndDate = createSelector(
  selectTransactionState,
  (state) => ({ start: state.start, end: state.end })
);

this is the dateRange reducer

  on(transactionActions.UpdateDateRange, (state, { start, end }) => ({
    ...state,
    start,
    end,
  })),

this is the date range action

export const UpdateDateRange = createAction(
  "[Transaction Page] Update Date Range",
  props<{ start: Date; end: Date }>()
);

this is my state

export interface State {
  transaction: Transaction[];
  cursors: Cursor;
  totalTransactions: number;
  loading: boolean;
  errorMessage: string;
  formErrorMessage: string;
  items_per_page: number;
  pageSizeOptions: number[];
  pageIndex: number;
  searchKey: string;
  formMessage: string;
  start: Date;
  end: Date;
  trans_type: string;
  base_type: string;
}
export const initialState: State = {
  transaction: [],
  cursors: {
    after: "",
    before: "",
    hasNext: false,
    hasPrevious: false,
  },
  totalTransactions: 0,
  loading: false,
  errorMessage: null,
  formErrorMessage: null,
  items_per_page: 5,
  pageSizeOptions: [2, 3, 5, 10, 15],
  pageIndex: 0,
  searchKey: "",
  formMessage: "",
  start: null,
  end: null,
  trans_type: null,
  base_type: null,
};

Anytime i dispatch a different action for example this.store.dispatch(transactionActions.ResetPageIndex());, my subscription for the date get triggered.

why is that ?

In my reducer i only update start and end date when UpdateDateRange action is dispatched.


Solution

  • The ngrx select operator utilizes the rxjs distinctUntilChanged operator to ensure that a selector only emits if its result has changed. Refer to the source code here: https://github.com/ngrx/platform/blob/a6fe92df3134b7a589a2e95abe0aea183b411f03/modules/store/src/store.ts#L249

    By default distinctUntilChanged uses an equality comparer (refer to https://www.learnrxjs.io/learn-rxjs/operators/filtering/distinctuntilchanged) and note 'object references must match!'

    Now to your selectStartAndEndDate selector - it returns an object.

    Furthermore, it returns a new instance of an object each time it executes. Because of this, the comparison in distinctUntilChanged always fails so the selector always emits.

    How to resolve it:

    // returned date will be considered equal next time so selector won't fire
    export const selectStartDate = createSelector(
      selectTransactionState,
      (state) => state.start
    );
    
    // same here
    export const selectEndDate = createSelector(
      selectTransactionState,
      (state) => state.end
    );
    
    // as input selectors didn't change, this won't fire either
    export const selectStartAndEndDate = createSelector(
      selectStartDate,
      selectEndDate ,
      (start, end) => ({ start, end })
    );
    

    Stackblitz: https://codesandbox.io/s/so-ngrx-selector-emit-1zxg1?file=/src/app/store/selectors.ts