I’m using the following code to store cart data into local storage
"use client";
import React, { useState, useEffect } from "react";
export default function Home() {
const [cartItems, setCartItems] = useState([]);
useEffect(() => {
const cartItemsData = JSON.parse(localStorage.getItem("cartItems"));
if (cartItemsData) {
console.log("loaded cart items data", cartItemsData);
setCartItems(cartItemsData);
}
}, []);
useEffect(() => {
console.log("storing cart items", JSON.stringify(cartItems));
localStorage.setItem("cartItems", JSON.stringify(cartItems));
}, [cartItems]);
return <div>{JSON.stringify(cartItems)}</div>;
}
The issue I’m having is that when the page reloads, it calls the use effect hook which pulls the data from local storage and after it calls the use effect hook with cartItems=[] from the initialisation of useState([]) which then wipes local storage and sets cartItems to [].
I tried loading the data from local storage in useState but I get an error as the window hasn’t loaded at that point.
How do I fix this?