I use ReactJs, I wanna push more items to the already exists item in localstorage but every time i reload localstorage is reset to undefined...
React.useEffect(() => {
localStorage.setItem("cartItems", JSON.stringify(cartItems));
if (localStorage.getItem("cartItems") !== null) {
try {
let existing = localStorage.getItem("cartItems");
if (existing !== JSON.stringify(cartItems)) {
try {
let newExist = JSON.parse(existing).push(cartItems);
localStorage.setItem("cartItems", newExist);
} catch (e) {
console.log("NOOOO")
}
}
} catch (error) {
console.log("CARTITMES Localstorage is empty")
}
} else {
console.log("Null Cartitems in localstorea")
}
})
localStorage.setItem("cartItems", JSON.stringify(cartItems));
might always set it to empty ("null" | "undefined"
), depending on whatcartItems
holds.cartItems
before the useEffect in second line? or possibly do aconsole.log(cartItems)
before calling the setItem and see what the value is first