Skip to content

Commit 2aa5438

Browse files
felixSchlethul
authored andcommitted
Apply middleware API function earlier
This change enables a hack that is employed in a fairly famous library called "redux-saga", where the middleware api is captured during the call the "applyMiddleware" and subsequently used to dispatch more actions and peek into state. Note that this change does neither force this hack on others or encourage it. There should be no observable change to existing codebases. Applying this function earlier also means that we don't have to redefine the function on every invocation and re-create the middlewareApi object. Finally, this is consistent with the implementation in the redux source code: https://github.com/reactjs/redux/blob/e2e9648b264224af68add35431898dafe26b0a09/src/applyMiddleware.js
1 parent 9248a7b commit 2aa5438

File tree

1 file changed

+16
-15
lines changed

1 file changed

+16
-15
lines changed

src/React/Redux.js

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -76,21 +76,24 @@ exports.dispatch_ = function dispatch_(thisForeign, action){
7676
exports.applyMiddleware = function applyMiddleware(middlewares){
7777
var middlewaresForeign = middlewares.map(function(middleware){
7878
return function(middlewareAPIForeign){
79-
return function(nextForeign){
80-
return function(actionForeign){
81-
function getState(){
82-
return middlewareAPIForeign.getState();
83-
}
79+
function getState(){
80+
return middlewareAPIForeign.getState();
81+
}
8482

85-
function dispatch(action){
86-
return function(){
87-
var actionForeignResult = makeActionForeign(action);
83+
function dispatch(action){
84+
return function(){
85+
var actionForeignResult = makeActionForeign(action);
8886

89-
var result = middlewareAPIForeign.dispatch(actionForeignResult);
87+
var result = middlewareAPIForeign.dispatch(actionForeignResult);
9088

91-
return result;
92-
};
93-
}
89+
return result;
90+
};
91+
}
92+
93+
var cont = middleware({ getState: getState, dispatch: dispatch })
94+
95+
return function(nextForeign){
96+
return function(actionForeign){
9497

9598
function next(action){
9699
return function(){
@@ -102,11 +105,9 @@ exports.applyMiddleware = function applyMiddleware(middlewares){
102105
};
103106
}
104107

105-
var middlewareAPI = {getState: getState, dispatch: dispatch};
106-
107108
var action = actionForeign.action;
108109

109-
var result = middleware(middlewareAPI)(next)(action)();
110+
var result = cont(next)(action)();
110111

111112
return result;
112113
};

0 commit comments

Comments
 (0)