infodev
infodev

Reputation: 5245

Redux - Ngrx action dispatch asynchronous treatment

I have a time slider that trigger action to filter data every change

this.selectedDate$
  .pipe(
    switchMap(elm => {
      this.selectedTime = elm.timeSelect;
      this.store.dispatch(new GetSchedulesByTime(elm.timeSelect.toString()));
      return this.store.pipe(select(selectSchedulings));
    })
  )
  .subscribe((schedules: ISchedule[]) => {
...});

GetSchedulesByTime update a store with new data;

selectSchedulings is a selector of this new data

What happens is when selectedDate the action is dispatched , selector still points to last state, so my treatment is distorted.

Here's my action code

case ESchedulesActions.GetSchedulesByTime: {
  let time = action.payload;
  return { ...state, actualTrips: [...(state.schedulings[time] || [])] };
}

And selector

export const selectSchedulings = createSelector(
  schedulings,
  (state: ISchedulesState) => state.actualTrips
);

How to be sure that selector is pointing to the new state before return it ?

Upvotes: 0

Views: 56

Answers (1)

The Cloud Guy
The Cloud Guy

Reputation: 982

Here's a little understanding on how the dispatch and select actually work.

Dispatch When you dispatch an action, it calls for an effect if it exists. The output of effect or the action payload is directly transferred to the reducer that updates the state.

select The selectors help you select a particular part of your state. this.store.select basically returns you an observable that you can subscribe to. This subscription means that anytime there is a change in state, your subscription callback will be called.

Hence, what you essentially need to do is to take out the selector and subscribe to it as shown below:

this.scheduling$ = this.store.select(scheduleSelectors.selectSchedulings);
this.scheduling$.subscribe((data)->{
//do something with the data
//This is called everything state changes
})

Thus, you do not need to pipe the selector each time. Just subscribing to it once is sufficient. On every dispatch of action, your state should change and that will in turn call the above subscription. To validate this fact, you can debug your code and check for yourself.

Upvotes: 1

Related Questions