Accessing State and Payload in NGRX Effect

930 views
Skip to first unread message

sugarflux

unread,
Jun 6, 2019, 11:22:40 AM6/6/19
to Angular and AngularJS discussion
Hi all

I've been searching for days and I'm still struggling to come up with a solution. I have an NGRX action that sets a 'currentId' and passes off to a success action. I'm passing in the action payload (which is required in the success action) but I would also like to compare against the existing 'currentId' with means accessing the state... 

Most solutions seem to suggest that 
withLatestFrom()

is the obvious solution, however, using withLatestFrom whilst providing no errors during build, seems to stop the effect from running at all.

Here is what i have currently, which works for the payload:

@Effect()
setCurrentId$: Observable<Action> = this.actions$.pipe(
ofType<actions.SetCurrentId>(actions.ActionTypes.SET_CURRENTID),
map(action => {
return new actions.SetCurrentIdSuccess({ Id: action.payload.Id });
})
);

What I would like to do is get the currentId from the state to compare against, ideally passing a new parameter to the success effect (something like isNew: boolean). According to other forums, this should work:

@Effect()
setCurrentId$: Observable<Action> = this.actions$.pipe(
ofType<actions.SetCurrentId>(actions.ActionTypes.SET_CURRENTID),
withLatestFrom(this.store.select(state => state.feature.currentId)),
map(([action, currentId]) => {
return new actions.SetCurrentIdSuccess({ Id: action.payload.Id, IsNew: (currentId !== action.payload.currentId) });
})
);

However, this effect doesn't even seem to run although it generates no errors on build. This should be so simple to access state from within the effect but I am obviously missing something!

Can anyone help please? Let me know if more information is required!

Thanks

~S~





Sander Elias

unread,
Jun 7, 2019, 2:00:51 AM6/7/19
to Angular and AngularJS discussion
Hi ~S~

I'm not really familiar with ngrx, but I would say the set action is done before you read it back. So the result of your withLatestFrom is already updated, 

Regards
Sander
Reply all
Reply to author
Forward
0 new messages