Reputation: 100
I don't understand in my code why when I click on my productBtn, my item in the local storage is replaced by the new one
buttonProduct = document.getElementById('productBtn');
buttonProduct.addEventListener('click', () => {
const storageCameras = localStorage.getItem('basketCameras') ? JSON.parse(localStorage.getItem('basketCameras')) : [];
storageCameras.push(product._id)
localStorage.setItem('basketCameras', JSON.stringify([product._id]));
})
}
because in my code, I get an element, then I push, and finally, I set
is it because every time I click on productBtn
I refresh my []?
I just want to add and display all my elements ( i got 5 items)
Upvotes: 0
Views: 45
Reputation: 655
You should use storageCameras variable
buttonProduct = document.getElementById('productBtn');
buttonProduct.addEventListener('click', () => {
const storageCameras = localStorage.getItem('basketCameras') ? JSON.parse(localStorage.getItem('basketCameras')) : [];
storageCameras.push(product._id)
localStorage.setItem('basketCameras', JSON.stringify(storageCameras));
})
}
Upvotes: 3