Can somebody help me to solve an issue with Next JS and localstorage. I am building an ecommerce app where when a user puts an item in their basket, I want to be able to save it to the local storage. My current implementation doesn't work and I am geting an error that says 'Cannot read property 'basket' of undefined'. Below is my code snippet.
export const StateProvider = ({ children }) => {
const initialState = () => {
if (typeof window !== 'undefined') {
return {
basket:
window.localStorage.getItem('basket') === null
? []
: window.localStorage.getItem('basket'),
viwedItems: [],
saved: [],
};
}
};
const [state, dispatch] = useReducer(productReducer, initialState());
const [durationNotification, setDurationNotification] = useState(true);
const [showMiniBasket, setMiniBasket] = useState(false);
useEffect(() => {
window.localStorage.setItem('basket', state.basket);
}, [state.basket]);
question from:https://stackoverflow.com/questions/66062892/how-to-setup-and-use-local-storage-in-next-js