Blog>
Snippets

Redux Middleware Customization

Demonstrate how to customize and apply middleware in Redux v5.0.0 using the configureStore method from Redux Toolkit.
import { configureStore } from '@reduxjs/toolkit';

// Define a custom middleware
const myLoggerMiddleware = storeAPI => next => action => {
  console.log('dispatching', action);
  let result = next(action);
  console.log('next state', storeAPI.getState());
  return result;
};
This is a custom middleware that logs every action dispatched to the store, and the next state after the action is processed. It uses the 'storeAPI' to access the dispatch and getState functions, 'next' to call the next middleware in the chain, and 'action' representing the dispatched action.
import rootReducer from './rootReducer'; // A root reducer you previously defined

// Configure the store with rootReducer and apply the middleware
const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(myLoggerMiddleware)
});
This code snippet imports the rootReducer and creates a Redux store using 'configureStore' method from Redux Toolkit. It applies the default middlewares that come with Redux Toolkit and adds the custom 'myLoggerMiddleware' at the end of the middleware chain.
<!-- index.html -->
<html>
<head>
  <title>Redux Middleware Customization</title>
</head>
<body>
  <div id='app'></div>
  <script src='path/to/bundled/javascript'></script>
</body>
</html>
This is the HTML structure where your bundled JavaScript file containing the Redux store and middleware configuration will be included.
/* styles.css */

/* Add any CSS styles if necessary for your application. This example does not require specific styles related to middleware. */
This is a placeholder for your CSS file. You can add styles for your application as needed, but middleware customization itself does not involve CSS.