I want to put the sum in my localStorage thanks to a function because, I have to work with the creation of function. When I put the total of my basket in my local storage, the nav changes number. So, when refreshing the page, the total is counted as one more article and I have an error on the html tag "nan".Can you explain to me what is wrong with my code ?
let totalityPrice = document.querySelector('.subtotal');
let products = [];
let Total = 0;
function displayProduct() {
if (localStorage.length > 0) {
for (let key in localStorage) {
let product = JSON.parse(localStorage.getItem(key));
document.querySelector('.cart span').textContent = localStorage.length;
if (product) {
products.push(key);
cartTablebody.innerHTML += `
<tr>
<td>${product.title}</td>
<td>${product.price / 100}</td> //price=API data//
</tr>
`;
Total += product.price / 100;
}
}
}
}
displayProduct();
function calculatePrice() {
totalityPrice.innerText = Total;
console.log(Total);
//localstoragesetItem//
}
calculatePrice();
It sounds like there's something in localStorage that isn't a cart item. Check that each item has all the required properties before processing it.
And instead of using localStoage.length as the product count in .cart span, use products.length.
let totalityPrice = document.querySelector('.subtotal');
let products = [];
let Total = 0;
function displayProduct() {
if (localStorage.length > 0) {
for (let key in localStorage) {
let product = JSON.parse(localStorage.getItem(key));
if (product && "title" in product && "price" in product) {
products.push(key);
cartTablebody.innerHTML += `
<tr>
<td>${product.title}</td>
<td>${product.price / 100}</td> //price=API data//
</tr>
`;
Total += product.price / 100;
}
}
}
}
displayProduct();
function calculatePrice() {
totalityPrice.innerText = Total;
console.log(Total);
document.querySelector('.cart span').textContent = products.length;;
}
calculatePrice();