Utilize localstorage with Redux and Next.js to initialize the state

Having an issue when attempting to populate the initial state from local storage in order to create a store. I encountered the following error message:

ReferenceError: localStorage is not defined

Here is my store configuration:

const store = createStore(reducer, {
    userInfo: {
        isLogged: false,
        items: localStorage.getItem("@items") || []
    }
})

Answer №1

In Next.js, local storage is not defined due to its server-side rendering nature. To incorporate Redux into your project, you can use the boilerplate provided by Next.js.

Check out this example of Redux Persist

This example demonstrates how Redux can be integrated with Redux Persist in Next.js. By using Redux, you can create a global state for your application and ensure some state values are accessible offline as well. Redux Persist allows you to store your states in the browser's local storage. Although there are different methods available for persisting states, this example showcases the integration of redux-persist with Redux in conjunction with Next.js's universal rendering approach.

Answer №2

function retrieveLocalData(key) {
    if (typeof localStorage !== 'undefined') {
        return localStorage.getItem(key);
    }
    return null;
}
function storeLocalData(key, value) {
    if (typeof localStorage !== 'undefined') {
        localStorage.setItem(key, value);
    }
}

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

Tips for boosting ViteJs development mode performance

One issue I am facing is the slow server performance during development mode. After starting the server and opening the page in my browser, I have to wait 3–6 minutes for it to load! Initially, ViteJs downloads a small amount of resources, but then the ...

The 'id' property cannot be accessed because the data has not been retrieved successfully

After loading my App, the data from Firebase is fetched in componentDidMount. I am currently passing postComments={comments} as a prop. However, before this happens, my app crashes with Cannot read property 'id' of undefined on line const c ...

Remove dynamically created elements from an AngularJS div

Is there a way to remove an item from the criteria list when clicking the delete button? Currently, only the filter is being refreshed and not the tables. Any suggestions on how to resolve this issue? HTML <ul class="list-unstyled"> <l ...

Is there a way to eliminate the line that appears during TypeScript compilation of a RequireJS module which reads: Object.defineProperty(exports, "__esModule", { value: true });?

Here is the structure of my tsconfig.json file: { "compileOnSave": true, "compilerOptions": { "module": "amd", "noImplicitAny": false, "removeComments": false, "preserveConstEnums": true, "strictNullChecks": ...

Is it possible to utilize the import feature to access and read a JSON file within a Next.js 13 API scenario?

Currently, in my Next.js 13 project, I am using the App Router feature to work with an API route that reads a file from a language folder within the resources directory. The code structure of this API is as follows: // app/api/file/[lang]/write/route.ts i ...

Step-by-step guide on setting up NextJS with NGINX

Recently, I successfully deployed a React app on a server by following these steps: Running npm run build Creating a server block and directing the root to my react app folder build (root /var/www/xfolder/build;) Restarting nginx using systemctl restart n ...

How can you set a condition for when no matches are found in a list filter?

I recently came across a fascinating example on W3 Schools that taught me how to implement a search filter. Below, I have customized it for everyone's reference. I am interested in modifying it to only display a list item with the message: No matche ...

What is the best way to trigger a function once another one has finished executing?

After opening the modal, I am creating some functions. The RefreshBirths() function requires the motherId and fatherId which are obtained from the getDictionaryMother() and getDictionaryFather() functions (these display my mothers and fathers on the page s ...

"The jQuery colorpicker function is not functioning properly when applied to newly added elements

I've got these amazing gadgets with a cool sliding box feature inside. Initially, there are two widgets visible on the page, but you have the option to add or delete a widget as needed. Within the sliding box, there is a color picker tool. Interestin ...

Disable, Hide, or Remove Specific Options in a Single Dropdown Selection

A challenge I am facing involves creating a form with multiple select options that need to be ranked by the user from 1-8. However, I am encountering some difficulties in hiding, removing, or disabling certain select options. Below is an excerpt from my f ...

Ways to avoid route change triggered by an asynchronous function

Within my Next.js application, I have a function for uploading files that includes the then and catch functions. export const uploadDocument = async (url: UploadURLs, file: File) => { const formData = new FormData(); formData.append("file" ...

Overlap of columns within a nested flexbox arrangement

While working with React and Styled Components, I encountered a problem of elements overlapping each other: https://i.stack.imgur.com/RuCYu.png There are a few instances of overlap, including: The padding below the <ul> element is colliding with ...

Managing messaging broadcasts for messenger bots by creating and retrieving unique identifiers

As a beginner using a starter project from glitch, I have a project set up at this link: I need help understanding how to obtain the message_broadcast_id and how to create it. This is how I usually create a normal message: function callSendAPI(messageDa ...

Having trouble combining different styles with Material-ui and Radium?

Trying to integrate Radium with Material-ui has presented a challenge. Attempting to apply multiple styles to a single Material-ui component results in no styling being applied. For instance, the following code fails to render any styling: <MenuItem st ...

Issues with AngularJS Directives not functioning properly when elements are added dynamically through an AJAX request

I am facing a scenario where I have a page featuring a modal window that is created using the AngularUI Bootstrap modal directive. The DOM structure for this modal is being dynamically loaded from the server, and it is triggered to open when a specific but ...

Encountering an undefined error while attempting to retrieve an object from an array by index in Angular

Once the page is loaded, it retrieves data on countries from my rest api. When a user selects a country, it then loads the corresponding cities for that country. Everything is functioning properly up to this point, however, upon opening the page, the city ...

How to Refresh EJS Template in an Express Node.js Application

Currently, I am integrating discord.js with express and facing a challenge. I want my webpage to automatically update whenever the client.on("message") event is triggered. According to my knowledge and research, it seems that rendering an ejs template is o ...

Configuring environment variables during Jest execution

A variable is defined in my `main.ts` file like this: const mockMode = process.env.MOCK_MODE; When I create a test and set the variable to true, it doesn't reflect as `'true'` in the main file, but as `'false'` instead. describe ...

Adjust the range directly in ng-repeat from the directive

I am working with HTML code that looks like this: <div dir-paginate="x in comments | itemsPerPage: commentsPerPage"> HERE IS DIRECTIVE FROM BLEOW </div> My goal is to update the commentsPerPage scope within the directive... Below is a direct ...

Nextjs has the ability to trigger a full page rerender once the entire page has finished

Working on a Next.js 14 application that utilizes Server-Side Rendering (SSR) to generate the complete HTML for the browser, I've come across an issue. After the page fully loads in the browser, Next.js triggers a re-render which briefly displays the ...