reactjstypescriptnext.jsredux-toolkitredux-persist

How to write redux-persist in redux toolkit along with TypeScript


I have been using Redux Persist in my next js application but now I want to use redux toolkit along with type script. Got the syntax to write redux-persist in redux toolkit but not able to find anything specific to typescript. Anyone please suggest a way to implement redux-persist with redux toolkit and typescript. Till now using this.

import { configureStore } from '@reduxjs/toolkit'
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from 'redux-persist'
import storage from 'redux-persist/lib/storage'
import { PersistGate } from 'redux-persist/integration/react'

import App from './App'
import rootReducer from './reducers'

const persistConfig = {
  key: 'root',
  version: 1,
  whitelist: [userReducer],
  storage,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

const store = configureStore({
 reducer: persistedReducer,
 devTools: process.env.NODE_ENV !== 'production',
 middleware: [thunk]
})

let persistor = persistStore(store)

ReactDOM.render(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>,
  document.getElementById('root')
)

Solution

  • I use redux toolkit and typescript, my store configuration looks like this:

    import { FLUSH, PAUSE, PERSIST, PURGE, REGISTER, REHYDRATE, persistStore } from 'redux-persist';
    
    import reducer from './rootReducer';
    
    const devToolsCompose = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;
    
    export const store = configureStore({
      reducer,
      devTools: { trace: true, traceLimit: 25 },
      middleware: [
        ...getDefaultMiddleware({
          serializableCheck: {
            ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER]
          }
        })
      ]
    });
    
    export type RootState = ReturnType<typeof store.getState>;
    export type AppDispatch = typeof store.dispatch;
    export const persistor = persistStore(store);
    

    Redux toolkit has docs for typescript here: https://redux-toolkit.js.org/usage/usage-with-typescript