Reputation: 4725
I was reading official tutorials about middlewares.
I am confused about this line of middleware code: next(action)
From my understanding, the next
function is actually store.dispatch
, and every Middleware will call next(action)
, wouldn't it dispatch that action multiple times?
So here are two Middlewares:
const logger = store => next => action => {
console.log('dispatching', action)
let result = next(action) // I'm talking about this line
console.log('next state', store.getState())
return result
}
const crashReporter = store => next => action => {
try {
return next(action) // This line too.
} catch (err) {
console.error('Caught an exception!', err)
Raven.captureException(err, {
extra: {
action,
state: store.getState()
}
})
throw err
}
}
Line 3 and 10 both call next(action)
, plus I have the very first store.dispatch(action)
, wouldn't that action be dispatched 3 times?
Wouldn't that break the app?
Upvotes: 0
Views: 229
Reputation: 177
From the applyMiddleware source code you have that dispatch
is modified as follows:
const fakeStore = {
getState: store.getState,
dispatch: (...args) => dispatch(...args)
}
const chain = middlewares.map(middleware => middleware(fakeStore))
dispatch = compose(...chain)(store.dispatch)
where compose is just function composition.
So if you called applyMiddleware(logger, crashReporter)
, then the argument next
of your logger
middleware would be just crashReporter(fakeStore)
, not dispatch
.
In general, next
would be the next middleware (hence the name).
Upvotes: 1