Reputation: 3219
I imagine this is a very common use case but can't find an example that clearly lays it out for me.
const openTriviaTokenEpic = (action$, store) =>
action$
.ofType(OT_GET_TOKEN)
.mergeMap(action =>
Observable.from(fetch(OPEN_TRIVIA_API + "api_token.php?command=request"))
.flatMap(res => Observable.from(res.json()))
.map(fetchRes => {
console.log("fetch sub token", fetchRes);
let actions = [getOpenTriviaTokenSuccess(fetchRes.token), getOpenTriviaQuestions()];
return Observable.from(actions);
})
)
.catch(result => Observable.of(getOpenTriviaTokenFailure({ message: "Unable to retrieve token for Trivia." })));
I see my fetch is happening, then I want to dispatch two actions:
I'm returning an Observable on those two actions but I get the following error in my console:
Uncaught Error: Actions must be plain objects. Use custom middleware for async actions. at Object.performAction
And my action is this:
export const getOpenTriviaTokenSuccess = payload => {
console.log("payload", payload);
return {
type: OT_GET_TOKEN_SUCCESS,
payload: payload
};
};
Any help?
Upvotes: 1
Views: 458
Reputation: 58400
If you're returning an observable, you'll need to use flatMap
instead of map
:
.flatMap(fetchRes => {
console.log("fetch sub token", fetchRes);
let actions = [getOpenTriviaTokenSuccess(fetchRes.token), getOpenTriviaQuestions()];
return Observable.from(actions);
})
Upvotes: 1