0

Where does thunk middleware come into place? This is the order of the middlewares that I see this going through right now but I get stuck on where Thunk comes in:

  1. dispatches action that has promise value set to true
  2. goes to thunk, thunk doesn't do anything with it because it's an object, not function
  3. goes to promiseErrorMiddleware, which gets store from applyMiddlware and returns a function.
  4. does this function get intercepted by Thunk even though it was returned, and not dispatched? who exactly runs this function that will return the next function with the action as an argument? who will then run that final function?

Store

const store = createStore(
  rootReducer,
  applyMiddleware(thunkMiddleware, promiseErrorMiddleware, dataTrafficMiddleware)
)

actionCreator

dispatch({url: requestURL, promise: true})

promiseErrorMiddleware & dataTrafficMiddleware

const promiseErrorMiddleware = function (store) { //where is store from, applyMiddleware?
      return function (next) { //where is next from?
        return function (action) {
          if (!action.promise) {
            return next(action)
          } else {
            return fetch(action.url).then(function (data) {
              ...
              next({data, needDirection: true})
            })
          }
        }
      }
    }

const dataTrafficMiddleware = function (store) {
  return function (next) {
    return function (action) {
      if (!action.needDirection) {
        return next(action)
      } else {
        //dispatch regular action with type and data
      }
      }
    }
  }
}
stackjlei
  • 9,485
  • 18
  • 65
  • 113
  • Possible duplicate of [Why do we need middleware for async flow in Redux?](http://stackoverflow.com/questions/34570758/why-do-we-need-middleware-for-async-flow-in-redux) – vijayst Sep 30 '16 at 02:54

1 Answers1

0

One thing to keep in mind is that the middlewares are chained. When you call next() it goes to the next middleware, in the order you defined them in applyMiddleware(). At the end of the middleware chain the action goes through the reducer(s). In your code, the function is never getting passed through the thunk middleware (since thunk comes before promiseErrorMiddleware). On the other hand, if you dispatch() the action, it will run through the entire middleware chain from the beginning.

bjudson
  • 4,073
  • 3
  • 29
  • 46