[Fixed] how to select form ngrx store within an Effect using a slector with parameters

Issue

I need to build an Effect and I need a value from the store, the problem is that the selector is a selector with parameters.

following the example code:

        @Effect()
      ExampleEffect$ = this.actions$.pipe(
        ofType(
          ActionTypes.SOMETHING
        ),
        map((action: Somthing) => action.payload.myParameter),
// HERE I NEED THE PARAMETER TO PERFROM THE SELECTION
        withLatestFrom(this.store.pipe(select(selectorWithParamter(myParameter))),
        map((value) => /* do somthing with the array [myParameter, valueSelected from sotre]*/)

Solution

You can write an arrow function to pass parameters while creating a selector.

export const getAlbumById = (collectionId: number) => createSelector(getAlbumEntities, entities => entities[collectionId]);

More example

// effect

@Effect({ dispatch: true })
  upsertAlbum$ = this.actions$.pipe(
    ofType(AlbumActionTypes.UpsertAlbum),
    map((action: any) => action.payload),
    mergeMap(({ album }) =>
      this.store.pipe(
        select(selectAlbumIfExists(album.id)),
        first(),
        map(isAlbumHasName => [album, isAlbumHasName])
      )
    ),
    filter(([album, isAlbumHasName]) => !isAlbumHasName),
    map(([album]) => new LoadAlbum({ album }))
  );

// selector

export const selectAlbumIfExists = (id: string) =>
  createSelector(
    selectAlbumsEntities,
    entities => !!(entities[id] && entities[id].name)
  );

Leave a Reply

(*) Required, Your email will not be published