Here I'm trying store the name of the id and the number of times it has been clicked.
It's stores as an object but when I tried JSON.Stringify()
it returns a empty array like this
'[]'
if (localStorage.getItem('cart') == null) {
var cartArr = {};
} else {
cartArr = JSON.parse(localStorage.getItem('cart'));
}
const cartClass = document.querySelectorAll(".cart");
cartClass.forEach((ele) => {
ele.addEventListener('click', (e) => {
let cartId = (e.target.getAttribute('id'));
if (cartArr[cartId] == undefined) {
cartArr[cartId] = 1;
} else {
cartArr[cartId] = 1;
}
localStorage.setItem('cart', JSON.stringify(cartArr));
console.log(localStorage.getItem('cart'));
});
});
CodePudding user response:
Your code should work. You never stored an array in that code. Perhaps you have another code that stored cart as an array?
I would delegate and give the system a tiny bit of time to react
const cartStr = localStorage.getItem('cart')
cartArr = cartStr ? JSON.parse(cartStr) : {}
const cartContainer = document.getElementById("cartContainer");
cartContainer.addEventListener('click', (e) => {
const tgt = e.target.closest(".cart");
if (tgt) {
let cartId = tgt.id;
cartArr[cartId] = cartArr[cartId] ? cartArr[cartId] : 0;
cartArr[cartId] ;
localStorage.setItem('cart', JSON.stringify(cartArr));
setTimeout(function() {
console.log(localStorage.getItem('cart'))
}, 10); // give the system time to react
}
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I have checked your code, it works correctly. Your problem can be solved by cleaning your localStorage
. It seems that at some point you have stored an empty array into your local storage. What happens is, JSON.stringify
stores the contents of array, but ignores any custom properties you set on an array object:
// This will log "[]"
const arr = [];
arr.prop = "val"
console.log(JSON.stringify(arr));
// This will log {"prop": "val"}
const obj = {};
obj.prop = "val"
console.log(JSON.stringify(obj));