Search code examples
reactjsreduxreact-reduxredux-toolkit

How to get middlewares from getDefaultMiddleware without deprecation message


I'm using a different setup for initializing the redux store (I don't want to use the configureStore method from redux-toolkit) for the purpose of injecting reducers on runtime.

import {
 createStore,
 combineReducers,
 applyMiddleware,
 createImmutableStateInvariantMiddleware,
 } from "@reduxjs/toolkit";
import { composeWithDevTools } from "@redux-devtools/extension";
import { createCustomMiddleWare} from "./myCustomMiddleWare"; 

const staticReducers = {};

const middlewares = [
createImmutableStateInvariantMiddleware(),
createCustomMiddleWare(),
];

const createReducer = (asyncReducers = {}) =>
combineReducers({
 ...staticReducers,
 ...asyncReducers,
});

export const initializeStore = (initializeState = {}) => {
  const store = createStore(
  createReducer(),
  initializeState,
  composeWithDevTools(applyMiddleware(...middlewares))
);
  store.asyncReducers = {};
  store.injectReducer = (key, reducer) => {
  store.asyncReducers[key] = reducer;
  store.replaceReducer(createReducer(store.asyncReducers));
  return store;
  };
  return store;
};

export default initializeStore;

I was wondering wether there is a way to add Thunk middleware from redux-toolkit (without installing the redux-thunk package seperately)

I tried using the getDefaultMiddleware() method from redux-toolkit which imports three default middlewares that ships with redux-toolkit including thunk, but since I'm not using it as paramether for the configureStore's middleware callback, I get this error that getDefaultMiddleware is deprecated.

I was able to import one of the default middlewares by using createImmutableStateInvariantMiddleware() function that I found in the official documentations but I could not find a way to import thunk or serlizied middlewares (two other default middlewares of redux-toolkit)


Solution

  • The answer would be to use configureStore and using the middleware callback option.

    There is really no good reason that would be using createStore here, that could come down to

    const store = configureStore({
      reducer: createReducer(),
      preloadedState: initializeState,
      middleware: getDefaultMiddleware => getDefaultMiddleware().concat(createCustomMiddleWare())
    })