Search code examples
javascriptreactjsrxjs5redux-thunkredux-observable

use of redux-thunk with redux-observable


I'm using redux-thunk to manage async stuff in my react application and I want to use redux-observable to manage complex async flow more easily (concat multiple Ajax calls for example). Is there a way to do so without modify what's already done?

Here's an example of what I mean:

const fetchSomeData = () => {
    return (dispatch, getState) => {
        doAnAjaxCall((err, response) => {
            if (err) return dispatch({type: 'ERROR', err})
            // do something
            return dispatch({type: 'SUCCESS', response})
        })
    }
}

Is it possible to use fetchSomeData inside an epic?
Since redux-thunk is promise based redux-observable should allow that, am I missing something?


Solution

  • Yep! You totally can use them together. Just place the redux-thunk middleware before the redux-observable middleware.

    applyMiddleware(thunkMiddleware, epicMiddleware)
    

    https://stackblitz.com/edit/redux-observable-playground-8c7pd9?file=ping-pong.js

    Redux applies middleware in the order they are provided as arguments, so in this case we want the thunk middleware to absorb any dispatched thunks so that the thunk functions themselves never reach redux-observable (only pure actions). But your epics can still dispatch thunks since the redux-observable middleware uses store.dispatch under the hood.