Muskan Rawal
Muskan Rawal

Reputation: 118

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')
)

Upvotes: 6

Views: 10074

Answers (2)

Joe Hong
Joe Hong

Reputation: 1

    /* copy link to see my solution:
    https://extreme-amethyst-885.notion.site/redux-persist-with-typescript-18cd5db1d68043ba81ac1b63fd64084c?pvs=4

store/hooks.ts
store/reducers.ts
store/store.ts

persist Gate hydration error handle*/
import { persistor, store } from "./store/store";
import { PersistGate } from "redux-persist/integration/react";

function App() {
return (
    <Provider store={store}>
            <PersistGate loading={null} persistor={persistor}>
              {() => (
                <YourApp />
              )}
            </PersistGate>
    </Provider>
)
export default App;

Upvotes: 0

MusicIsFreedom
MusicIsFreedom

Reputation: 76

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

Upvotes: 5

Related Questions