Search code examples
angularrxjsngrx

Get store item in Effect


I have a small Effect and I need to get the action data (nanoId) and I need to select data with this nanoId in store:

  @Effect()
  syncObj$ = this.actions$.pipe(
    ofType(ObjActions.Actions.SYNC_NEW_OBJ),
    mergeMap(({nanoId, obj}) => {
      this.store.pipe(select(getObjByNanoId(nanoId), first())).subscribe(eObj => {
        // return [] <-- error if I try to return pipe result here and remove return below
      })
      return [] // <-- this is below return
    }
    )
  );

I thought of withLatestFrom() but it needs an additional pipe, as I understand. My goal is to catch an object and nanoId from action, then select an object with nanoId in store (eOnj) and compare some of it's fields. Thanks!


Solution

  • Note, you don't have to subscribe inside withLatestFrom since it requires an observable.

     @Effect()
      syncObj$ = this.actions$.pipe(
        ofType(ObjActions.Actions.SYNC_NEW_OBJ),
        mergeMap(action => {
         
          return of(action).pipe(
            withLatestFrom(
              this.store.pipe(select(getObjByNanoId(nanoId)),
            )
          )
        }),
        mergeMap(([action, obj]) => {
          // code here
        })
    
      );