How to remove the localStorage entirely without localStorage.clear(); method?
I have a cart where you can store the products you're about to buy and the storing happens with a local storage. Currently the "Clear Cart" button works with localStorage.clear(); method, but I also have a table where you can remove single products. However, if you remove the entire table with the "remove" button on the same row and it happens to be the last product, local storage will still have an empty array and is considered as NOT null.
This is my method to remove the item:
function removeItem(itemId) {
//removes the parent row of table
$('#product-table').on('click', '.remove-item', function(e) {
$(this).closest('tr').remove();
});
var index = -1;
var obj = JSON.parse(localStorage.getItem("items")) || {}; //fetch cart from storage
var items = obj || []; //get the products
$.each(items, function(key, value) {
if (key === itemId) {
items.splice(key, 1); //remove item from array
}
});
localStorage.setItem("items", JSON.stringify(obj)); //set item back into storage
sum = 0;
$.each(items, function(key, value) {
sum += value.itemPrice;
});
$("#summary").html(sum.toFixed(2) + "€");
updateCartCount();
}
It removes items correctly, but whenever I remove the last product, the table element and add a paragraph saying "Your cart is empty. Return to shop".
Following function is below:
function hideElements() {
if ($(".cart-wrapper").length) {
if (localStorage.getItem("items") === null) {
$("#products").css("display", "none");
$("#empty").css("display", "block");
$(".btn-clear").css("display", "none");
} else {
$("#products").css("display", "block");
$("#empty").css("display", "none");
$(".btn-clear").css("display", "block");
}
}
}
The hideElements function won't recognize the local storage as empty, since it shows that there is an empty array object.
How can I achieve this by removing the entire local storage, if the removed product was the last product on the cart? I tried out with localStorage.getItems("items").length != 0 and such with no avail.
The following image displays my "empty" local storage:

.removeItem( 'items' )andif (localStorage.getItem("items"))? Since localStorage items are always strings, checking the length of the string without parsing it, will give the wrong result since an empty array has length 0, but the string representing an empty array"[]", has length 2.