I got following erros in my next.js 13 project please help me to fix this problem.
[1] - error srcreduxstore.js (12:15) @ localStorage
[1] - error ReferenceError: localStorage is not defined
this is how it looks in my terminal
this is my store.js file
`import { createStore, combineReducers, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import { rootReducer } from "./rootReducer";
const finalReducer = combineReducers({
rootReducer,
});
const intialState = {
rootReducer: {
cartItems: localStorage.getItem("cartItems")
? JSON.parse(localStorage.getItem("cartItems"))
: [],
},
};
const middleware = [thunk];
const store = createStore(
finalReducer,
intialState,
composeWithDevTools(applyMiddleware(...middleware))
);
export default store;`
please help me to fix this error
2
Answers
Follow this link, there’s something related:
Solve ReferenceError: localStorage is not defined in Next.js
Maybe it’s just a hydration issue? Window.localstorage is a browser reserved variable but not so for server. Couldn’t you just give a default value that both server and browser can consume and then once browser loads you update the variable? ( for example with a useEffect )