I am writing a custom middleware that needs to dispatch thunk actions. The problem is that the middleware is called after redux-thunk
in the middleware chain, so I get the error Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
when using the provided dispatch
.
export default function createMiddleware() {
return ({dispatch, getState}) => next => (action) => {
if(action.type !== 'FOO') {
return next(action);
}
dispatch(thunkActionHere); // this is the issue
}
}
I would like to dispatch this thunk action back to the beginning of the middleware chain so that redux-thunk can handle it. Is this possible?
update:
function createMiddleware(extraArgument) {
return function ({dispatch, getState}) {
return function (next) {
return function (action) {
switch (action.type) {
case 'FOO1':
dispatch({type: 'NORMAL_ACTION'}); // works fine
break;
case 'FOO2':
dispatch(function() {
return (dispatch, getState) => { // Error: Actions must be plain objects. Use custom middleware for async actions.
console.log('inside the thunk');
};
});
break;
default:
return next(action);
}
};
};
};
}
const middleware = createMiddleware();
middleware.withExtraArgument = createMiddleware;
export default middleware;
Here's my store configuration:
export default function configureStore(initialState) {
const store = createStore(rootReducer, initialState, compose(
// Add other middleware on this line...
applyMiddleware(bugsnagErrorCatcherMiddleware()),
applyMiddleware(thunk.withExtraArgument({APIFactory, PusherManager})),
applyMiddleware(webrtcVideoMiddleware.withExtraArgument(PusherManager)), // this is the middleware above
applyMiddleware(bugsnagbreadcrumbLoggerMiddleware()),
)
);
return store;
}
I cannot put my middleware before redux-thunk because then it doesn't receive actions that thunks dispatch.