7

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") || []
    }
})
  • It seems this above code was running on server which is node env so how do you have localStorage? So check if window defined or not first to determine if this browser then proceed next – tmhao2005 Aug 06 '20 at 04:46

2 Answers2

8

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.

Hamed Rahimi
  • 144
  • 1
  • 5
1

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);
    }
}
Mark Simon
  • 612
  • 1
  • 6
  • 17
  • 4
    In Next.js everything is server-side rendered and if the initial render client side does not match server side there will be an HTML mismatch warning. Also the client side version of the page will be discarded. So we can't use this method alone to cause the page to render differently. – Michael Fulton Jun 06 '21 at 06:11