Reputation: 103
I am studying Redux-Toolkit studio, and in particular, I am approaching custom middleware.
Below I report the definition of my store within my classic application example:
import { combineReducers, configureStore} from '@reduxjs/toolkit';
import {todosSlice} from '.. /features/todos/todosSlice';
import { filterStore } from '.. /features/todos/filterSlice';
import { myLog } from '.. /reduxtoolkitmiddlewarecustom/myLog';
const rootReducer = combineReducers({
todos: todosSlice.reducer,
filter: filterStore.reducer
});
export const store = configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) => getDefaultMiddleware(). concat(myLog),
});
As you see in the store amount, the middleware "custom" defined in '.. /reduxtoolkitmiddlewarecustom/myLog';
The definition of middleware is as follows:
export const myLog = (store) => {
console.log('Init myLog');
return function myDispatch(next) {
return function myAction(action) { //action is the action received from the store.
store.Dispatch({ type: 'INIT_MYLOG', payload: null });
console.log(action);
//return next(action);
}
}
};
Well, if I emit a Dispatch, I do not return next(action), is that the return I still get an error of "Uncaught Rangeerror: Maximum call stack size exceeded".
I thought I understood, but evidently, I don't. The only way to make the code work is, for example, to make a console.log What am I tripping about? If found the error, in general, if the middleware makes a Dispatch in the store, must a corresponding reducer/action creator exist?
Thank you so much
Upvotes: 1
Views: 754
Reputation: 44136
your middleware dispatches INIT_MYLOG
on every action. and that dispatched INIT_MYLOG
then triggers your middleware. and that then dispatches. an endless circle.
Solution? Don't dispatch in a middleware except if you do it as a reaction to one specific action.
Upvotes: 2