1

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:

Local Storage

1
  • 1
    .removeItem( 'items' ) and if (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. Commented Jul 25, 2019 at 13:12

2 Answers 2

4

What localstorage.get() returns is a string rather than JSON so what you need to do is parse string i.e. localStorage.getItem('items') returns "[]" which has length equal to 2. What you need to do is JSON.parse(localstorage.getItem('item')).length

Sign up to request clarification or add additional context in comments.

1 Comment

Actually this worked for my case; modified to this code if (JSON.parse(localStorage.getItem('items')).length === 0) { clearCart(); }
3

You're probably looking for localStorage.removeItem().

Better yet, you should refactor things so there are functions solely responsible for managing the items array in your local storage:

function loadItems() {
  // Returns the value of items, or an empty array.
  return JSON.parse(localStorage.getItem("items") || "[]");
}

function saveItems(itemsArr) {
  localStorage.setItem("items", JSON.stringify(itemsArr));
}

// Remove item with given ID (assuming each element in the array is e.g. `{id: 123}`)
const itemId = 123;
saveItems(loadItems().filter(item => item.id !== itemId));

// Update cart HTML elements:
if ($(".cart-wrapper").length) {
  const haveItems = loadItems().length > 0;
  $("#products").toggle(!haveItems);
  $("#empty").toggle(haveItems);
  $(".btn-clear").toggle(!haveItems);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.