Search code examples
reactjsreact-reduxrtk-query

How to use two API reducer with RTK query in configuration Store?


I tried to combine two RTK reducers, but every time I tried to use concat to include it in the middleware, there will be errors, here's my code

store.ts

import { configureStore,combineReducers } from "@reduxjs/toolkit";
import cartReducer from "./cartRedux";
import userReducer from "./authRedux";
import { AuthAPI } from "./authRTK";
import { cartAPI } from "./cartRTK";
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from "redux-persist";
import storage from 'redux-persist/lib/storage'


const persistConfig = {
  key: "root",
  blacklist:['AuthAPI','cartAPI'],
  storage,
};
const rootReducer = combineReducers({
    [cartAPI.reducerPath]: cartAPI.reducer,
    [AuthAPI.reducerPath]: AuthAPI.reducer,
    auth:userReducer,
    cart:cartReducer,
})

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = configureStore({
  reducer: persistedReducer,
//   reducer: {
//     cart: cartReducer,
//     auth: persistedReducer,
//     [api.reducerPath]: api.reducer,
//   },
  middleware: (gDM) =>
    gDM({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }).concat([AuthAPI.middleware,cartAPI.middleware]), //getDefaultMiddleware
});

export let persistor = persistStore(store);

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;

// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;

enter image description here

The reported error is like the below pic, I can't figure out what's the error really about.

Is something wrong with how I use multiple APIs? since there's no combine version in the official documents.


Solution

  • I would assume that both cartAPI and AuthAPI have a reducerPath of query, leading to a conflict. You need to give them different reducerPaths.

    That said, it is highly advised not to have more than one api in your whole application unless those query truly independent data with no overlap ever. (That would be the case if querying for google and twitter, since those are two independent companies, but not if querying Posts and Comments since these might be linked).