Redux newbie here. I understand the core concept of actions, middleware, and reducers, but one of the code snippets works not as I expected. I don't think that it's a bug, but I want to know why things happened in that way.
So, here is a code:
const middlewareOne = store => next => action => {
console.log('Middleware one recived action', action.type)
switch (action.type) {
case 'A':
return next({ type: 'B' })
default:
return next(action)
}
}
const middlewareTwo = store => next => action => {
console.log('Middleware two recived action', action.type)
switch (action.type) {
case 'B':
store.dispatch({ type: 'D' })
return next({ type: 'C' })
default:
return next(action)
}
}
function reducer(state, action)
console.log('Reducer received action', action.type)
return state
}
I have actions A, B, C, and D, two middlewares, and reducer. First middleware receives action A and produces action B by calling next() function.
Second middleware receives action B and produces action C, and, dispatches an action D.
As I understand, there is nothing wrong with dispatching actions from middleware, but the result was very surprising for me.
Here is a console output for this code
Middleware one receive action A
Middleware two receive action B
Middleware one receive action D
Middleware two receive action D
Reducer received action D
Reducer received action C
So, what I except: As I know, next() function passes the action to the next middleware or to the reducer if there are no middlewares in the chain, but dispatch puts action to the beginning of the pipeline (all middlewares and finally, the reducer). So, with that idea in mind, I think that action C will be reduced at first (since it's already in the middlewares pipeline), and only after that middlewares start to processing action D, but the result is completely opposite. Can you please explain to me why this happens.
Best regards, Vitaly Sulimov.