I am currently in apprenticeship and I am having a problem. I must be able to modify the quantity of the product or remove it from my basket. (therefore modify the localStorage) But I cannot do it, I am aware that this question must have been asked several times. But I can't find an answer to my problem among the many documentations, I must go about it wrong.
let basket = JSON.parse(localStorage.getItem("Sofas")) || [];
const cartItems = document.getElementById("cart__items");
contentBaskets = [];
function onQuantityChange(id) {
}
for (let i = 0; i < basket.length; i++) {
fetch("http://localhost:3000/api/products/" + basket[i].id)
.then((response) => response.json())
.then((data) => {
contentBaskets =
contentBaskets +
`<article class="cart__item" data-id=${basket[i].id}>
<div class="cart__item__img">
<img src=${data.imageUrl}>
</div>
<div class="cart__item__content">
<div class="cart__item__content__titlePrice">
<h2>${data.name}</h2>
<p>${data.price}€</p>
</div>
<div class="cart__item__content__settings">
<p>Couleur : ${basket[i].color}</p>
<div class="cart__item__content__settings__quantity">
<p>Qté : </p>
<input type="number" class="itemQuantity" name="itemQuantity" min="1" max="100" value=${basket[i].quantity} onchange=onQuantityChange('${basket[i].id}')>
</div>
<div class="cart__item__content__settings__delete">
<p class="deleteItem">Supprimer</p>
</div>
</div>
</div>
</article>`;
if (basket.length) {
cartItems.innerHTML = contentBaskets;
}
});
}
I'm not sure what's your question, but here's how to edit an object in localStorage.
// Get the string that's stored in localStorage
const stored = localStorage.getItem("sofas")
// Parse
const array = JSON.parse(stored) || []
// Push a new sofa to the array
array.push("IKEA Friheten")
// Set to localStorage the stringified version
// of the array, so you can get it later
localStorage.setItem("sofas", JSON.stringify(array))