I am trying to add a custom middleware to a store already using RTK Queries. But I get the "Warning: Middleware for RTK-Query API at reducerPath "api" has not been added to the store." error at runtime, although I did add the api middleware. Here is my store.ts file:
import { combineReducers, configureStore } from '@reduxjs/toolkit'
import { apiSlice } from './apiSlice'
import { homeModeReducer, workingReducer, bannersReducer, latestEventDataReducer } from './reducers/reducers'
import { useDispatch, useSelector, TypedUseSelectorHook } from 'react-redux'
import { latestMiddleware } from './middleware'
const reducer = combineReducers({
[apiSlice.reducerPath]: apiSlice.reducer,
mode: homeModeReducer,
working: workingReducer,
banners: bannersReducer,
latestEventData: latestEventDataReducer
})
const store = configureStore({
reducer,
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(latestMiddleware).concat(apiSlice.middleware)
})
export default store
export type RootState = ReturnType<typeof reducer>;
export type AppDispatch = typeof store.dispatch
export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
and my middleware is defined as:
import { Middleware } from 'redux'
import { RootState } from './store'
export const latestMiddleware: Middleware<
{}, // Most middleware do not modify the dispatch return value
RootState
> = storeApi => next => action => {
console.log(action.type)
return storeApi.getState() // correctly typed as RootState
}
It compiles correctly but fails at runtime. Any help?
CodePudding user response:
Your latestMiddleware
is not calling next(action)
, which means that the next middleware (and finally, the reducer) will never be executed.