Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux Observable: How to use action.payload in latter part of chain?

I've ran into this issue quite a few times where I want to access action.payload further down the chain. But by then, the argument passed to mergeMap has already changed to something else.

Given 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's 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 would I do this?

like image 706
bigpotato Avatar asked Jul 19 '17 06:07

bigpotato


1 Answers

This trick is to just place your second mergeMap inside the closure where the action is available. In fact, even if you didn't need access to it I generally recommend this pattern in redux-observable whereby you isolate your Observable chains inside your single top-level merging strategy operator (mergeMap, switchMap, etc) because it makes future refactoring like this easier as well as easier error isolation (if added).

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;
          // ...
        });
    });
}

Your example contained Observable.fromPromise() which I assume is just pseudo code, so I followed suit with Observable.fromPromise(somePromise) for more clarity for other readers.

like image 57
jayphelps Avatar answered Sep 28 '22 08:09

jayphelps