Skip to content

Commit 50dd790

Browse files
committed
Warn when dispatching during middleware setup.
1 parent 780adbd commit 50dd790

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/applyMiddleware.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import compose from './compose'
2+
import warning from './utils/warning'
23

34
/**
45
* Creates a store enhancer that applies middleware to the dispatch method
@@ -19,7 +20,13 @@ import compose from './compose'
1920
export default function applyMiddleware(...middlewares) {
2021
return (createStore) => (reducer, initialState, enhancer) => {
2122
var store = createStore(reducer, initialState, enhancer)
22-
var dispatch = store.dispatch
23+
var dispatch = (...args) => {
24+
warning(
25+
`Calling dispatch while constructing your middleware is discouraged. ` +
26+
`Other middleware will not be applied to this dispatch.`
27+
)
28+
store.dispatch(...args)
29+
}
2330
var chain = []
2431

2532
var middlewareAPI = {

test/applyMiddleware.spec.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,20 @@ import { addTodo, addTodoAsync, addTodoIfEmpty } from './helpers/actionCreators'
55
import { thunk } from './helpers/middleware'
66

77
describe('applyMiddleware', () => {
8+
it('warns when dispatching during middleware setup', () => {
9+
function dispatchingMiddleware(store) {
10+
store.dispatch(addTodo('Dont dispatch in middleware setup'))
11+
return next => action => next(action)
12+
}
13+
14+
const spy = expect.spyOn(console, 'error')
15+
16+
applyMiddleware(dispatchingMiddleware)(createStore)(reducers.todos)
17+
18+
expect(spy.calls.length).toEqual(1)
19+
spy.restore()
20+
})
21+
822
it('wraps dispatch method with middleware once', () => {
923
function test(spyOnMethods) {
1024
return methods => {

0 commit comments

Comments
 (0)