customuserlink
customuserlink

Reputation: 89

Load the initial state with localstorage Redux + Next.js

I'm trying to load the initial state from localstorage to create store, but i got this error: ReferenceError: localStorage is not defined

My store:

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

Upvotes: 8

Views: 7964

Answers (2)

Mark Simon
Mark Simon

Reputation: 752

const getStorLocal = (item) => {
    if (typeof localStorage !== 'undefined') {
        return localStorage.getItem(item);
    }
    return null;
}
const setStorLocal = (item, value) => {
    if (typeof localStorage !== 'undefined') {
        localStorage.setItem(item, value);
    }
}

Upvotes: 2

Hamed Rahimi
Hamed Rahimi

Reputation: 163

local storage is not defined in next js because it renders in server side to implement your Redux use this boiler Plate by Next js.

Redux Persist example

This example shows how to integrate Redux with the power of Redux Persist in Next.js.

With the advantage of having a global state for your app using redux. You'll also require some of your state values to be available offline. There comes redux-persist using which you can persist your states in browser's local storage. While there are various ways of persisting your states which you can always find in there documentation. This is an example of how you can integrate redux-persist with redux along with Next.js's universal rendering approach.

Upvotes: 8

Related Questions