Redux Observable: how to use action.payload in the second part of the chain?

I came across this problem quite often when I want to access action.payloadfurther down the chain. But by then, the argument passed in mergeMaphad already changed to something else.

Given that my action looks like this:

{
  type: BUY_GEMS,
  payload: { value: 123, productIdentifier: "ABC123" }
}

And this epic:

function purchaseGems(action$, store) {
  return action$
    .ofType(BUY_GEMS)
    .mergeMap(action => {
      const { productIdentifier } = action.payload; // <-------- works because it the first mergeMap in this sequence
      return Observable.fromPromise(
        // Some promise call
      ).catch(error => Observable.of(buyGemsRejected(error)));
    })
    .mergeMap(action => {
      const { value } = action.payload; // <----------- doesn't work because "action" is now just the response of the Promise above.
      ...
    });
}

How should I do it?

+4
source share
1 answer

, mergeMap , . , , , Observable (mergeMap, switchMap ..), , ( ).

function purchaseGems(action$, store) {
  return action$
    .ofType(BUY_GEMS)
    .mergeMap(action => {
      const { productIdentifier } = action.payload;
      return Observable.fromPromise(somePromise)
        .catch(error => Observable.of(buyGemsRejected(error)))
        .mergeMap(response => {
          const { value } = action.payload;
          // ...
        });
    });
}

Observable.fromPromise(), , , , Observable.fromPromise(somePromise) .

+6

Source: https://habr.com/ru/post/1681758/


All Articles