Have you ever wondered why the cart object is saved as "cart" in the local storage instead of being an actual object? This discrepancy is causing the cart not to display correctly.
This issue arose after deploying the website on Vercel. Storing "cart" as a string rather than an object is leading to errors.
You can visit the site here:
@Yogi expressed concerns that my initial explanation was insufficient. The cart object is initially created within the addToCart method... When there are no items in the cart, it creates the cart object with the key item code and values such as quantity, price, name, size, variant...
if (itemCode in cart) {
newCart[itemCode].qty = cart[itemCode].qty + qty
}
else {
newCart[itemCode] = { qty: 1, price, name, size, variant }
}
After deployment on Vercel, the JSON.stringify converted "cart" in the local storage as depicted in the image below..
Here is the code snippet:
const [cart, setCart] = useState({})
const [subTotal, setSubTotal] = useState(0)
useEffect(() => {
try {
if (localStorage.getItem("cart")) {
setCart(JSON.parse(localStorage.getItem("cart")));
saveCart(JSON.parse(localStorage.getItem("cart")));
}
}
catch (error) {
console.error(error);
localStorage.clear;
}
}, [])
const saveCart = (myCart) => {
localStorage.setItem("cart",JSON.stringify(myCart))
let subt = 0;
let keys = Object.keys(myCart)
for (let index = 0; index < keys.length; index++) {
subt += myCart[keys[index]].qty * myCart[keys[index]].price
}
setSubTotal(subt)
}
const addToCart = (itemCode, qty, price, name, size, variant) => {
let newCart = cart;
if (itemCode in cart) {
newCart[itemCode].qty = cart[itemCode].qty + qty
}
else {
newCart[itemCode] = { qty: 1, price, name, size, variant }
}
setCart(newCart);
saveCart(newCart);
}