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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With