Home > database >  NgRx: How to console.log a store.select from inside an effect?
NgRx: How to console.log a store.select from inside an effect?

Time:03-19

I'm learning NgRx and trying to console.log some values selected from the store inside an effect. I don't know much of RxJs. When I try, it's showing something like this, instead of a number:

enter image description here

Here is the code:

resetSample$= createEffect(() => this.actions$.pipe(
    ofType(DecisorActions.ResetSampleAction),
    map(() => { 
        this.file.readlineGuard(); // throw EOF error

        // I would like to console.log() those number values:
        console.log(this.store.select(Selectors.getA)));
        console.log(this.store.select(Selectors.getB)));
        console.log(this.store.select(Selectors.getC)));

        console.log('RESET SAMPLE EFFECT');

        return DecisorActions.BuyAction({payload: 0});
    }),
    catchError( err => { console.log('EOF detected'); return of(DecisorActions.EndOfFileError({payload:0})); })
));

If I'm missing some important concepts, I would also appreciate recommendations of what to read / look for.

CodePudding user response:

A good resource to look at would be NgRx Encorprating State, which uses concatLatestFrom. Alternatively you can use the RxJs operator withLatestFrom. From that NgRx link, it states:

When state is needed, the RxJS withLatestFrom or the @ngrx/effects concatLatestFrom operators can be used to provide it.

Essentially you'd have something along the lines of:

resetSample$= createEffect(() => this.actions$.pipe(
    ofType(DecisorActions.ResetSampleAction),
    withLatestFrom(
      this.store.select(Selectors.getA),
      this.store.select(Selectors.getB),
      this.store.select(Selectors.getC)
    ),
    map(([action, a, b, c]) => { 
        this.file.readlineGuard(); // throw EOF error

        // Log values here:
        console.log(a);
        console.log(b);
        console.log(c);

        console.log('RESET SAMPLE EFFECT');

        return DecisorActions.BuyAction({payload: 0});
    }),
    catchError( err => { console.log('EOF detected'); return of(DecisorActions.EndOfFileError({payload:0})); })
));

Note: If using version 6 of RxJS, only 5 arguments are allowed within withLatestFrom. See this Github issue.

Starting from version 7, the code was updated to allow any number of arguments. See the code for the operator here.

  • Related