Search code examples
rxjsstatengrxchainingpayload

Access to state and payload data together inside ngrx effect


I save in ngrx state some widget instance (third party non angular library) and I need to update widget with new params by user action. For this case I dispatch action with new widget params as payload.

It is possible to get payload and state data in same place of effect without additional private field?

@Effect({ dispatch: false })
public updateStatistics: Observable<webChatActions.Actions> = this._actions.pipe(
    ofType(Types.UPDATE_STATISTICS),
    map((action: demoActions.UpdateStatistics) => action.payload),
    tap((payload: StatisticsOptions) => console.log(payload)),
    withLatestFrom(this._store),
    map(([action, state]): DemoEffects => state['web-chat']),
    tap((state: WebChatState) => {
    // here I have my state, but also I need payload from tap above
    }),
    catchError((error: Error) => {
        this._logger.error('unable to update feedback widget', error);
        return of(new webChatActions.Service.ShowChatError(error));
    })
);

Solution

  • Remove the map and you have it.

    @Effect({ dispatch: false })
    public updateStatistics: Observable<webChatActions.Actions> = this._actions.pipe(
        ofType(Types.UPDATE_STATISTICS),
        map((action: demoActions.UpdateStatistics) => action.payload),
        tap((payload: StatisticsOptions) => console.log(payload)),
        withLatestFrom(this._store),
        map((): DemoEffects => state['web-chat']),
        tap(([action, state]) => {
          // action.payload 
          // tate['web-chat']
        }),
        catchError((error: Error) => {
            this._logger.error('unable to update feedback widget', error);
            return of(new webChatActions.Service.ShowChatError(error));
        })
    );