I have integrated redux-persist into my Next.js project. The issue I am facing is that the state is getting saved in localStorage when the store is updated, but it gets reset every time the page changes. I suspect the problem lies within one of the reducers and could possibly be related to Server-Side Rendering (SSR).
import { createSlice, PayloadAction } from "@reduxjs/toolkit"
import { HYDRATE } from "next-redux-wrapper";
import { searchStateType } from "../../models/reducerModels/reducerModels";
const initialState: searchStateType = {
dataBar:
{
location: '',
date: {
from: undefined,
to: undefined
},
number: {
adults: 1,
child: 0,
rooms: 1
}
}
}
const searchDataSlice = createSlice({
name: 'search',
initialState,
reducers: {
updateSearchbarData: (state, action: PayloadAction<searchStateType>) => {
state.dataBar = { ...action.payload.dataBar }
}
},
extraReducers: {
[HYDRATE]: (state, action) => {
return {
...state,
...action.payload.search
}
},
}
})
export const { updateSearchbarData } = searchDataSlice.actions
export default searchDataSlice.reducer
Store Configuration
const makeStore = () => {
const isServer = typeof window === "undefined";
const rootReducer = combineReducers({
search: searchDataReducer,
userData: userDataReducer,
regions: regionsIdReducer,
loading: visibleLoadingReducer,
hotelsRegion: hotelsRegionReducer,
hotelsId: hotelsIdReducer,
room: roomBookingReducer,
webRoom: webRoomBookingReducer,
bookingRoomData: bookingRoomsUserDataReducer,
});
if (isServer) {
const store = configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
immutableCheck: false,
serializableCheck: false,
}),
});
return store;
} else {
const persistConfig = {
key: "nextjs",
storage,
whitelist: ['search']
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = configureStore({
reducer: persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
immutableCheck: false,
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
});
(store as any).__persistor = persistStore(store)
return store;
}
};
export const store = makeStore()
export type RootStore = ReturnType<typeof makeStore>;
export type RootState = ReturnType<RootStore['getState']>;
export type AppThunk<ReturnType = void> = ThunkAction<ReturnType, RootState, unknown, Action>;
export type AppDispatch = typeof store.dispatch
export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
export const wrapper = createWrapper<RootStore>(makeStore);
If you have any insights on solving this issue, please share them with me.