Blog>
Snippets

Migrating to RTK 2.0's Enhanced Middleware API

Provide an example of the new middleware API in Redux Toolkit 2.0, focusing on how to inject dependencies into a custom middleware.
import { configureStore, createAction, createReducer } from '@reduxjs/toolkit';

// Define a custom action
const fetchData = createAction('fetch/data');

// Define a simple reducer
const dataReducer = createReducer([], {
  [fetchData]: (state, action) => [...state, action.payload],
});
First, import necessary functions from Redux Toolkit. Define a custom action to fetch data and a simple reducer to handle that action by adding the fetched data to the state.
const myCustomMiddleware = ({ dispatch, getState }) => next => action => {
  // Handle the action in your middleware here
  console.log('Action received:', action);
  return next(action);
};
Create a custom middleware using the curried function format. This middleware simply logs out every action it receives before passing it on to the next middleware in the chain.
import { createMiddleware } from '@reduxjs/toolkit';

const myEnhancedMiddleware = createMiddleware({
  middleware: myCustomMiddleware,
  // ... You can inject dependencies here
});
Using Redux Toolkit 2.0's enhanced middleware API, wrap the custom middleware with `createMiddleware`. This is where you can inject additional dependencies if needed.
const store = configureStore({
  reducer: {
    data: dataReducer,
  },
  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(myEnhancedMiddleware),
});
Finally, configure the Redux store by combining the reducer and the enhanced middleware. The default middleware is included by calling `getDefaultMiddleware` and then the custom middleware is appended to the middleware chain using `.concat()`.