Reputation: 89
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
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
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.
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