redux-toolkit: [getDefaultMiddleware] problem that the type of ReturnType becomes any

Problem

import { configureStore } from '@reduxjs/toolkit';
import {
  FLUSH,
  PAUSE,
  PERSIST,
  persistReducer,
  persistStore,
  PURGE,
  REGISTER,
  REHYDRATE
} from 'redux-persist';
import storage from 'redux-persist/lib/storage';

const persistConfig = {
  key: 'hoge',
  version: 1,
  storage
};

export const store = configureStore({
  reducer: persistReducer(persistConfig, rootReducer),
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER]
      }
    })
});

export type RootState = ReturnType<typeof store.getState>;

type RootState = any

No Problem

import { configureStore } from '@reduxjs/toolkit';
import storage from 'redux-persist/lib/storage';

const persistConfig = {
  key: 'hoge',
  version: 1,
  storage
};

export const store = configureStore({
  reducer: persistReducer(persistConfig, rootReducer)
});

export type RootState = ReturnType<typeof store.getState>;

In this case, the type is correctly defined.

Why does passing getDefaultMiddleware make the type definition any?

Please help to fix this problem. Thanks!

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 5
  • Comments: 23

Most upvoted comments

Like I said earlier, this seems to happen when you do two things together:

  • put a function call on the right-hand side of reducer: (in other words, calling function A and passing its result immediately as part of the field being defined)
  • Also call middleware: getDefaultMiddleware => getDefaultMiddleware()

Your last example is doing exactly that. There’s a connectRouter() call being used as an argument to configureStore() , and you are using getDefaultMiddleware().

The workaround, as mentioned earlier, is to not have any function calls on the right-hand side of reducer: .

So, change it to:

const rootReducer = combineReducers({
  ...reducerMap,
    router: connectRouter(history)
})

const store = configureStore({
  reducer: rootReducer, // NO FUNCTION CALLS HERE NOW,
  middleware: gDM => gDM().concat(middlewares)
})

we can’t help you without seeing your actual code, and like i said this is a separate issue.

at a random guess, it sounds like you could be doing middleware: (getDefaultMiddleware) => { getDefaultMiddleware() } instead of middleware: (getDefaultMiddleware) => getDefaultMiddleware()

same problem .It took me almost 1 hour to reach this page

faced this issue too 😦 My codesandbox And yes, when I make reducer outside of configureStore - it’s working.