rt2zz / redux-persist

persist and rehydrate a redux store
MIT License
12.94k stars 866 forks source link

Using RTK Query along with Redux persist. #1432

Closed anusaraweerasooriya closed 1 year ago

anusaraweerasooriya commented 1 year ago

Hello everyone! After spending large amount of time trying to fix this issue alone, I thought asking help from you guys. I have read so many issues regarding this but couldn't find anything helpful. I am trying to configure my store using both persistorand RTK Query. this is my index.js file where I am trying to configure the store

const persistConfig = { key: "root", storage, version: 1 };

const persistReducers = persistReducer(persistConfig, authReducer);

const store = configureStore({
  reducer: {
    [customApi.reducerPath]: customApi.reducer,
     persistReducers,
  },

  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }).concat(customApi.middleware),
});
setupListeners(store.dispatch);

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistStore(store)}>
        <App />
      </PersistGate>
    </Provider>
  </React.StrictMode>
);

This is my RTK Query

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { REHYDRATE } from "redux-persist";

export const customApi = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_BASE_URL }),
  reducerPath: "customApi",
  tagTypes: ["RuralProjects"],
  endpoints: (build) => ({
    getRuralProjects: build.query({
      query: () => "projects/ruralProjects",
      providesTags: ["RuralProjects"],
    }),
  }),
});

export const { useGetRuralProjectsQuery } = customApi;

This is my authReducer

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  user: null,
  token: null,
};

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    setLogin: (state, action) => {
      state.user = action.payload.user;
      state.token = action.payload.token;
    },
    setLogout: (state) => {
      state.user = null;
      state.token = null;
    },
  },
});

export const { setLogin, setLogout } = authSlice.actions;
export default authSlice.reducer;

The thing is without configuring the RTK Query in store my app is working. My question is how to use both persistorand RTK Query at the same time? Any help would be appreciated a lot!