Search code examples
angularrxjsngrxngrx-effects

NgRx Effects - change stream payload in effect before another effects


I've been wondering if there is a way to change the stream's payload in the NgRx effect before another NgRx effect is executed. I have three actions where I need to add multiple values (for all three actions are always the same values) from the ngrx state into the payload and think about using one effect instead of calling concatLatestFrom from each effect separately.

addValuesToPayloadOfActions$ = createEffect(() => {
return this.actions$.pipe(
  ofType(
    actions.action1,
    actions.action2,
    actions.action3
  ),
  concatLatestFrom(() => [
    this.store.pipe(select(getSomeStoreValue)),
    this.store.pipe(select(getSomeStoreValue2))
  ]),
  map(([action, storeValue, storeValue2]) => {

    const payload = {
      ...action.payload,
      storeValue,
      storeValue2
    };

    return payload;
  })
)}, 
{ dispatch: false });

and then I have also effects listening for action1, action2, action3 separately.

Right now addValuesToPayloadOfActions is executed, but it does not change payload of action1, action2, action3.


Solution

  • Right now addValuesToPayloadOfActions is executed, but it does not change payload of action1, action2, action3.

    What makes you think that this effect modifies the action?

    I think what you're trying to do is to dispatch a new action that includes all the details. For this, you should create a new action and dispatch the action instead of having the effect configured with {dispatch:false}.

    addValuesToPayloadOfActions$ = createEffect(() => {
    return this.actions$.pipe(
      ofType(
        actions.action1,
        actions.action2,
        actions.action3
      ),
      concatLatestFrom(() => [
        this.store.pipe(select(getSomeStoreValue)),
        this.store.pipe(select(getSomeStoreValue2))
      ]),
      map(([action, storeValue, storeValue2]) => {
    
        const payload = {
          ...action.payload,
          storeValue,
          storeValue2
        };
    
        return action.action4(payload);
      })
    )});