Search code examples
reduxredux-toolkitredux-persistrtk-query

What happens when i use RTK Query with redux-persist?


What will happen when i use Redux Toolkit Query with redux-persist?

Will it use the persisted state or will the state be refetched?


Solution

  • There is an official guide for this now. At the time of writing this, you could configure it this way:

    // store.ts
    import { configureStore, combineReducers } from '@reduxjs/toolkit'
    import {
      persistStore,
      persistReducer,
      FLUSH,
      REHYDRATE,
      PAUSE,
      PERSIST,
      PURGE,
      REGISTER,
    } from 'redux-persist'
    import AsyncStorage from '@react-native-async-storage/async-storage'
    
    import someSlice from 'config/features/someSlice'
    import { api } from 'config/services/api'
    
    const reducers = combineReducers({
      someSlice,
      [api.reducerPath]: api.reducer,
    })
    
    const persistConfig = {
      key: 'root',
      version: 1,
      storage: AsyncStorage,
    }
    
    const persistedReducer = persistReducer(persistConfig, reducers)
    
    export const store = configureStore({
      reducer: persistedReducer,
      middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
          // Redux persist
          serializableCheck: {
            ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
          },
        }).concat(
          api.middleware,
        ),
    })
    
    export let persistor = persistStore(store)
    
    export type RootState = ReturnType<typeof store.getState>
    export type AppDispatch = typeof store.dispatch
    
    // App.tsx for native or index.tsx
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <App />
        </PersistGate>
      </Provider>,