Search code examples
angulartypescriptngrxngrx-storengrx-effects

Need to write ngRx selector to select data between given date range?


I need to write a selector to select the entity array list data. The data array objects content startDate and EndDate. but some object doesn't have the end date. I need to check the end date, if -> endDate available. if the end date is null, that data also should be added to the map. need some expert help to correct this selector logic. It will be given sonar issue also need to use '!==' and 'Variables should not be shadowed' like one too 'select all' .

Start, End -> check Pass date between or Equal date range

The only start -> Check start date on or before the given date.

My date selected logic:

   const selectReviewState =
  createSelector(selectAdminFeature,
    (appState) => appState.ReviewState);

const {
  selectAll,
} = ReviewAdaptor.getSelectors();

/**
 * Select all Review as an array
 */
const selectReviews = createSelector(
  selectReviewState,
  selectAll
);

/**
 *
 * Select Review data with in given range , during one year period past to future
 *
 */
export const selectAllReviewsDetailsModel = (planedDate: Date) => createSelector(
  selectReviews,
  (selectAll: ReviewModel[]) =>
    selectAll.filter(date => date.startDateTime.getTime() <= planedDate.getTime() &&
      (date.endDateTime != null && date.endDateTime.getTime() >= planedDate.getTime()))
);

Solution

  • moment is very robust date library that can make the date computations easy. you can update the selector like below

    import moment from 'moment';
    
    export const selectAllReviewsDetailsModel => createSelector(
      selectReviews,
      (selectAll: ReviewModel[], props) => {
        const { planedDate } = props;
        return selectAll.filter(date => 
            moment(date.startDateTime).isSameOrBefore(moment(planedDate)) &&
            moment(date.endDateTime).isValid() ? moment(date.startDateTime).isSameOrAfter(moment(planedDate)) : true)
      });
    

    if you notice i am passing the planedDate as props and on the component side you can use this selector

    const result = this.store.pipe(selectAllReviewsDetailsModel, { planedDate: '09/12/2002' })