ngrx router store selector in effect

261 Views Asked by At

Let's say I have a list and a pagination in my app. And I have this state:

{
  ...
  itemsPerPage: number;
  searchPhrase?: string;
}

Also, I have to have a pageIndex (current page no) and I get it from Url. For that, I have a selector:

export const getCurrentPageIndex = createSelector(
  selectRouteParam("pageIndex"),
  (pageIndex) => {
    return pageIndex ? parseInt(pageIndex, 10) : 1;
  }
);

and my route has {:pageIndex} parameter. So far so good.

Now, I have an effect that deals with loading data for the current page and it gets all required parameters from state (including pageIndex using mentioned selector) using withLatestFrom() and then request data from the server. So simple scenario like changing the page work.

Now, imagine having a Filter field where user can type something in and this something goes into searchPhrase and then I need to refresh the page BUT I need to set the current page number (pageIndex) to 1. And this pageIndex comes from router store. So, here's what I do in effects:

  loadPageByNumber$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(MyActions.loadPageByNumber),
        tap((action) => {
          this.router.navigate([`/someroute/${action.pageIndex}`]);
        }),
        map(() => MyActions.loadPageOfData({}))
      )
    //{ dispatch: false }
  );

and here's the problem. Even though I do navigate to new page the effect loadPageOfData() still sees the old pageIndex from the router store selector.

For example, the route /items/30 - gets 30th page of data. Now, user types in the search phrase - the state changes and I need to reset pageIndex to 1 (because this is now completely different set of data). My logic doesn't work, the pageIndex stays the same inside the loading data effect.

How can I fix this or what am I doing wrong here?

0

There are 0 best solutions below