Skip to content

Don't break middleware with internal dispatch. #3020

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions src/applyMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,17 @@ import compose from './compose'
export default function applyMiddleware(...middlewares) {
return createStore => (...args) => {
const store = createStore(...args)
let dispatch = () => {
throw new Error(
`Dispatching while constructing your middleware is not allowed. ` +
`Other middleware would not be applied to this dispatch.`
let dispatch = (...args) => {
console.warn(
`You are attempting to dispatch from within a middleware during "applyMiddleware". ` +
`Other middleware will not be applied to this dispatch.`
)
store.dispatch(...args)
}

const middlewareAPI = {
getState: store.getState,
dispatch: (...args) => dispatch(...args)
dispatch
}
const chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch)
Expand Down
11 changes: 0 additions & 11 deletions test/applyMiddleware.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,6 @@ import { addTodo, addTodoAsync, addTodoIfEmpty } from './helpers/actionCreators'
import { thunk } from './helpers/middleware'

describe('applyMiddleware', () => {
it('warns when dispatching during middleware setup', () => {
function dispatchingMiddleware(store) {
store.dispatch(addTodo('Dont dispatch in middleware setup'))
return next => action => next(action)
}

expect(() =>
applyMiddleware(dispatchingMiddleware)(createStore)(reducers.todos)
).toThrow()
})

it('wraps dispatch method with middleware once', () => {
function test(spyOnMethods) {
return methods => {
Expand Down