javascript - What does it mean for an action to travel through an entire middleware chain in redux? -
looking @ react-redux docs, don't below how why having action travel whole middleware useful:
it bit of trickery make sure if call store.dispatch(action) middleware instead of next(action), action travel whole middleware chain again, including current middleware. useful asynchronous middleware, have seen previously.
what mean action travel through middleware? how affect dispatch? understanding dispatch changes through each layer of middleware goes through, , next
refers previous middlware's dispatch, whereas dispatch
refers original store.dispatch.
as can see in the middleware example, there multiple middleware items create pipe:
rafscheduler -> timeoutscheduler -> thunk -> vanillapromise -> etc...
an action travels middleware items before getting base reducer or being intercepted 1 of middleware items. each middleware item can decide move action next middleware in chain using next()
. however, want action travel chain start.
for example, using redux thunk, dispatch async action, handled thunk middleware. async action dispatch action, when async call succeeds. action should start again rafscheduler
middleware.
if dispatch have worked next, travel vanillapromise
middleware instead. solve that, dispatch(action)
, no matter called, travels chain start.
to create behavior applymiddleware()
runs on middleware store => next => action
methods, passes middlewareapi
api store
param, passes, , overrides store.dispatch
, new dispatch combined middleware. magic happens - new dispatch chain of middleware methods, each calls 1 after when next invoked (next = next middleware method), , last ones next()
old store.dispatch
calls base reducer:
export default function applymiddleware(...middlewares) { return (createstore) => (reducer, preloadedstate, enhancer) => { var store = createstore(reducer, preloadedstate, enhancer) var dispatch = store.dispatch // original dispatch var chain = [] /*** store param of middleware ***/ var middlewareapi = { getstate: store.getstate, dispatch: (action) => dispatch(action) } /*** store param applied old middlewares create chain ***/ chain = middlewares.map(middleware => middleware(middlewareapi)) /*** chain composed. methods in chain, last, next() middleware method after in chain, last next store.dispatch ***/ dispatch = compose(...chain)(store.dispatch) return { ...store, dispatch // new dispatch returned instead of old } } }
Comments
Post a Comment