When refreshing the page, redux-persist clears the state

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.

Answer №1

const searchDataSection = createSlice({
   name: 'search',
   initialState,
   reducers: {
      searchInput: (state, action: PayloadAction<searchStateType>) => {
         state.dataBar = { ...action.payload.dataBar }
      }
   },
   extraReducers: {
      [HYDRATE]: (state, action) => {
         let searchResults = { ...action.payload.search };
         delete searchResults.PERSISTED_FIELD

         return {
            ...state,
            ...searchResults
         }
      },
   }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered in NextJS middleware: NetworkError occurred while trying to retrieve resource

I'm currently working with a middleware setup in NextJS based on an old tutorial. The code provided in the tutorial seems to be functioning correctly, but when I implement the same code, I encounter a NetworkError. Upon further investigation, it appea ...

An anchor-shaped name tag with a touch of flair

I stumbled upon this unique anchor name design on the website Does anyone here know how to create something similar? What is that style called? ...

Switching effortlessly between Fixed and Relative positioning

As I work on creating a unique scrolling experience, I aim to have elements stop at specific points and animate before returning to normal scroll behavior once the user reaches the final point of the page. Essentially, when div X reaches the middle of the ...

Secure your text input with a masked Textfield component in Material-UI

I'm struggling to implement a mask for a TextField component, but so far I have not been successful. Although I attempted this solution, it did not work. No matter what method I try, the masking functionality just won't cooperate. Following the ...

Switching on the click functionality

I was able to successfully toggle a boolean variable along with some other options. However, I encountered an issue when trying to create another click function for a different button to set the boolean variable to false. Here is my code: let manageme ...

ClickAwayListener's callback function stops executing midway

I am currently utilizing Material-UI's ClickAwayListener in conjunction with react-router for my application. The issue I have come across involves the callback function of the ClickAwayListener being interrupted midway to allow a useEffect to run, on ...

Issue with Typescript and react-create-app integration using Express

I'm relatively new to Typescript and I decided to kickstart a project using create-react-app. However, I encountered an issue while trying to connect my project to a server using express. After creating a folder named src/server/server.ts, React auto ...

What is the best way to include the API body in a GET request?

I'm facing an issue with passing parameters to the body instead of the query in my code. Here's what I have attempted: const fetchData = async () => { let response = await apiCall("URL" + { "companyArr": ["SBI Life Insurance C ...

Encountering an error in a React application with Redux: "Unable to access the 'state' property of undefined"

I'm currently working on a react redux application where I want to add a message to the message array in the reducer's initial state when the add message button is pressed. However, I encountered an error "TypeError: newstate1.user.id.find is not ...

What is the proper way to send properties to a component that is enclosed within a Higher Order Component?

I have a situation where I need to pass props from the index page to a component wrapped inside two higher-order components. Despite fetching the data successfully in getStaticProps, when passing the props to the About component and console logging them in ...

RTL mode causing issues with Bootstrap breadcrumb functionality

I'm currently working on integrating a Bootstrap breadcrumb into my next.js application. Everything seems to be functioning correctly when in LTR mode, following the sample code provided in Bootstrap's documentation. However, when attempting to s ...

Ensuring Proper Tabulator Width Adjustment Across All Browser Zoom Levels

<div id="wormGearTabulatorTable" style="max-height: 100%; max-width: 100%; position: relative;" class="tabulator" role="grid" tabulator-layout="fitDataTable"><div class="tabulator-header" role="rowgroup"><div class="tabulator-header-co ...

Utilizing clip-path polygons for effective styling on Firefox and iOS

I have been working on a plugin to create animated modal boxes by utilizing the clip-path property. However, I have encountered an issue where this code only seems to work in Chrome. You can view the codepen demo here. Unfortunately, it appears that Firef ...

What is the method for retrieving a specific value following the submission of an AngularJS form?

Here is how my form begins: <!-- form --> <form ng-submit="form.submit()" class="form-horizontal" role="form" style="margin-top: 15px;"> <div class="form-group"> <label for="inputUrl" class="col-sm- ...

Leverage the controller's properties and methods within the directive

My situation involves a variety of inputs, each with specific directives: <input mask-value="ssn" validate="checkSsn"/> <input mask-value="pin" validate="checkPin"/> These properties are managed in the controller: app.controller("Ctrl", [&ap ...

Error in NextJS: The name 'NextApplicationPage' cannot be found

const { Component, pageProps}: { Component: NextApplicationPage; pageProps: any } = props After implementing the code above with 'Component' type set to NextApplicationPage, an error message pops up stating, The name 'NextApplicationPage&ap ...

Encountering a problem with AngularJS when attempting to access an array and display an alert message

While working with Angular, I encountered an issue in trying to access content stored within an array. Upon reviewing the code, console.log(JSON.stringify($scope.lineItems)) was returning [[]]. However, when inspecting or setting a breakpoint on this line ...

Passing along the mouse event to the containing canvas element that utilizes chart.js

Recently, I created a custom tooltip for my chart.js chart by implementing a div that moves above the chart. While it works well, I noticed that the tooltip is capturing mouse events rather than propagating them to the parent element (the chart) for updati ...

Implementing server authentication for page requests in a nodeJS and angularJS application

My application relies on passport.js for authentication. One of my main requirements is to prevent access to a specific page (e.g., '/restricted') for users who are not logged in. Currently, anyone can directly access the "localhost:3000/#/restr ...

You are unable to assign a string value instead of an object when making multiple selections

Utilizing react-select for autocomplete and option-related field has been quite helpful. However, I have noticed that in a single selection scenario, the code provided below only works when sending the value as a string. Unfortunately, it does not function ...