Search code examples
javascriptreactjsreduxreact-reduxmiddleware

passing middle ware to redux store using configure store function


I'm trying to make a simple gitHub profile reviewing react app, and I'm learning middleWare at the moment but I seem to have a little bit of problem applying it when I pass the middleWare to configureStore it seem to be not recieving it properly

this is the code in my index.js:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { configureStore, applyMiddleware } from '@reduxjs/toolkit';
import theReducer from './Store/reducer';
import { Provider } from 'react-redux';

const logger = store => next => action =>{
  console.log('[middleWare] Dispatching' , action);
  const result = next(action);
  console.log('[middleWare] next state' , store.getState());
  return result;
}
const middleWare = applyMiddleware(logger);

const store = configureStore({ reducer: theReducer}, middleWare);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
    <App />
    </Provider>
  </React.StrictMode>
);


reportWebVitals();

and when I'm dispatching an action to reducer I was expecting my actions and store to appear in my console, then I suspected maybe I'm not dispatching my actions properly and I applyed this middleWare to an other react app where I learned redux (the counter app that every one teaches react-redux with) where I knew that dispatching actions were working and the reslt was the same. the only thing that was diffrent was they passed their middleWare to createStore function like this: const store = createStore(reducer, middleware); but I can't use this anymore as the new configureStore function is the thing right now. how can I pass my middleWare to store using configureStore function? Is it even possible?


Solution

  • well, I really should have looked deeper to redux documentation :) ,here is the answer I was looking for:

    https://redux-toolkit.js.org/api/getDefaultMiddleware

    getDefaultMiddleware is useful if you want to add some custom middleware, but also still want to have the default middleware added as well:

    const store = configureStore({reducer: theReducer,
     middleware(getDefaultMiddleware)=>getDefaultMiddleware().concat(logger)});