Bilal
Bilal

Reputation: 11

How to use RTK query and redux thunk in same react app?

I have requirement where I have to use RTK query for data fetching and Redux-thunk for global state management. For the same I have created 2 separate stores, one for RTK and another for redux. Now I am facing issue as we should not have 2 stores in our application.

store 1:-

import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import combineReducer from './combineReducer';

export const configureStore = () : any => {
  const middleWares = [thunk];
  const middlewareEnhancer = applyMiddleware(...middleWares);

  const enhancers = [middlewareEnhancer];
  const composedEnhancers: any = compose(...enhancers);

  const store = createStore(combineReducer, composedEnhancers);

  return store;
};

store 2:-


import { configureStore } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/query";
import { postApi } from "../services/posts";

export const store = configureStore({
  reducer: {
    [postApi.reducerPath]: postApi.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(postApi.middleware),
});

setupListeners(store.dispatch);

App.tsx:-

const App: React.FC = () => (
  <Provider store={store}>
  <Provider store={rtkStore}>
    <Suspense fallback={<div>Loading...</div>}>
      <BrowserRouter>
        <Routes />
      </BrowserRouter>
    </Suspense>
  </Provider>
  </Provider>
);

I am sure, there is something fishy in this. Any solution for requirement would be appreciable.

Upvotes: 0

Views: 1853

Answers (1)

phry
phry

Reputation: 44086

Redux Toolkit comes with thunk per default. You do not need to set it up. RTK Query internally is based on thunks. You cannot have multiple Redux stores in one application.

Just create one store with configureStore, also add your other reducers there and use that for everything.

Generally we recommend in the Redux style guide to use Redux Toolkit for all your Redux logic, as helpers like createSlice massively reduce your boilerplate code and guard against most common bugs. This is the default recommendation for over two years now.

I would highly recommend you to read the official Redux Essentials tutorial if you haven't already.

Upvotes: 2

Related Questions