I am having issues pulling data from local storage in my next.js e-commerce app. Originally I am saving items to cart from within my cart-context file and with useReducer. In the cart provider component I am involving useEffect and setting the cartState to local storage with JSON.stringify(); I just learned that useReducer accepts a third argument that can return value and from the way I understand it, overrides the passing initial state. In this anonymous function I am making a call to localStorage to check if there is any "local data" and to return parsed local data if so. I am getting an error saying that local storage is not defined.. any help is greatly appreciated.
const CartProvider = (props) => {
const [cartState, dispatchCartState] = useReducer(
reducerFN,
initialCartState,
() => {
let localData = localStorage.getItem("items");
return localData ? JSON.parse(localData) : [];
}
);
useEffect(() => {
localStorage.setItem("items", JSON.stringify(cartState));
}, [cartState]);