Search code examples
angulartypescriptreduxrxjsngrx

Weird behavior when using ngrx effect with withLatestFrom operator


I have below selector

export const selectUserData = createSelector(selectState, state => {
    return state.user;
});

And in my effect, if I'm using withLatestFrom without []

withLatestFrom(
     this.commonStore.pipe(select(selectUserData))
)

loadUser$ = createEffect(() =>
        this.actions$.pipe(
            ofType(UserActionsTypes.GetUserSuccess),
            withLatestFrom(
                this.commonStore.pipe(select(selectUserData))
            ),
            mergeMap(([_, user]) => { 
                  console.log(user);

}

The console.log will return null data

But If I add [] to withLatestFrom

withLatestFrom(
     [this.commonStore.pipe(select(selectUserData))]
)

Then I will get data using subscribe in mergeMap

console.log(user.subscribe(x => console.log(x)));

Please note that the selector is having data and I check in redux devtool the data exist.

Any idea of how it happened?


Solution

  • I found the problem must be race condition on another effect I was listening on when using withLatestFrom operator so I do was change the of type to GetInitDataSuccess (CommonActionsType.GetInitDataSuccess action was fired before GetUserSuccess)

    ofType(CommonActionsType.GetInitDataSuccess)
    withLatestFrom(
                this.commonStore.pipe(select(selectUserData))
            ),
            mergeMap(([_, user]) => { 
                  console.log(user);