Home > Software design >  reactjs persist config required for persistReducer
reactjs persist config required for persistReducer

Time:07-21

I am developing an application with reactjs and I am using redux as my state management tool.

I want to use redux-persist to persist my data that I fetch from the server

but I am getting this error

Uncaught Error: config is required for persistReducer
    at persistReducer (persistReducer.js:25:1)
    at redux.js:468:1

My code

mport { configureStore, combineReducers } from '@reduxjs/toolkit'
import userReducer from './UserSlice'
import storage from 'redux-persist/lib/storage'

import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from 'redux-persist'



const rootReducer = combineReducers({user: userReducer})

This is where I create the persist config

const persistConfigs = {
  key: 'root',
  version: 1,
  storage,
}

Here is where I used the persist config

const persistedReducer = persistReducer(persistConfigs, rootReducer)

export const store = configureStore({
  reducer: {
    reducer: persistReducer,  
    middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
  },
})

export const persistor = persistStore(store)

UserReducer

This is the userSlice that I imported in store.js, the userSlice update the state when the user logs into the system.

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  currentUser: null,
  loading: false,
  error: false
}

it has 3 state: the starting state when the user click on submit button, the successful state if the user logs in successfully and failed state where the login fails

export const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
     loginStart: (state) => {
        state.loading = true;
     },
     loginSuccess: (state, action) => {
        state.loading = false;
        state.currentUser = action.payload;
     },
     loginFail: (state) => {
        state.loading = false;
        state.error = true;
     },
     logout: (state) => {
        state.loading = false;
        state.error = false;
        state.currentUser = null;
     }
    },
  })

  export const {loginStart, loginSuccess, loginFail, logout} = userSlice.actions

  export default userSlice.reducer;

Link to sandbox

https://codesandbox.io/s/wizardly-wing-jsv617

CodePudding user response:

You should use persistedReducer as a reducer and not persistReducer

const persistedReducer = persistReducer(persistConfigs, rootReducer)

export const store = configureStore({
  reducer: {
    reducer: persistedReducer,  
  • Related