Noah Bergh
Noah Bergh

Reputation: 495

Ngrx Effects How to get the payload of the previous action

If you've the following effect

  testEffects$ = createEffect(() => this.actions$.pipe(
    ofType(RDX_TEST_INC_VALUE),
    switchMap(ac => instance.get('/api/test/kam').then(res => {
      return {
        type: RDX_TEST_INC_VALUE_SUCCESS,
      }
    }).catch((err: AxiosError) => {
      return {
        type: RDX_TEST_INC_VALUE_ERROR,
      }
    }))
  ))

How do we return the payload of RDX_TEST_INC_VALUE with RDX_TEXT_INC_VALUE_SUCCESS?

Upvotes: 2

Views: 910

Answers (2)

timdeschryver
timdeschryver

Reputation: 15505

You can just use the payload

  testEffects$ = createEffect(() => this.actions$.pipe(
    ofType(RDX_TEST_INC_VALUE),
    switchMap(ac => instance.get('/api/test/kam').then(res => {
      return {
        type: RDX_TEST_INC_VALUE_SUCCESS,
        // 👇 we can just grab the payload from the action
        payload: ac.payload
      }
    }).catch((err: AxiosError) => {
      return {
        type: RDX_TEST_INC_VALUE_ERROR,
      }
    }))
  ))

Upvotes: 2

Loop
Loop

Reputation: 510

Depending on exactly you want to achieve, something like this should work

  testEffects$ = createEffect(() => this.actions$.pipe(
    ofType(RDX_TEST_INC_VALUE),
    withLatestFrom( from(instance.get('/api/test/kam'))),
    map(([action, promsieResult] => {
      // do whatever you want here
    }))
    catchError((err: AxiosError) => {
      return {
        type: RDX_TEST_INC_VALUE_ERROR,
      }
    }))
  ))

If you want withLatestFrom or something else depends on your use case. See https://www.learnrxjs.io/learn-rxjs/operators/combination for reference. I also converted your promise into an observable via the from Operator as described in Convert Promise to Observable. Much easier to handle inside the stream.

PS: Do not use forkJoin, it will not work with an action observable stream because it never completes.

Upvotes: 0

Related Questions