Remove an item from local storage in reactjs

19,743

Solution 1

To remove items from your local storage, you simply have to run:

localStorage.removeItem("name of the item")

Solution 2

    let items =JSON.parse(localStorage.getItem("item"));
    items = items.filter((item) => item.id !== id);
    localStorage.setItem("item", JSON.stringify(items));
    if (items.length === 0) {
      localStorage.removeItem("item");
    }
Share:
19,743

Related videos on Youtube

Abhishek Konnur
Author by

Abhishek Konnur

Mobile Photography, Traveler || HTML5, CSS3, Bootstrap, Uikit, Nodejs, Mongodb, Expressjs, Reactjs

Updated on June 04, 2022

Comments

  • Abhishek Konnur
    Abhishek Konnur almost 2 years

    Is this the right code to remove an item from localStorage:

    onDelete(name) {
            console.log("ProductList.onDelete: ", name);
            let {products} = this.state;
            products = products.filter(product => product.name !== name);
            this.setState({products});
            localStorage.setItem('products', JSON.stringify(products));
    }
    
    • Abhishek Konnur
      Abhishek Konnur almost 6 years
      localStorage.removeItem(); is used then how to get the exact item to be removed.
  • Abhishek Konnur
    Abhishek Konnur almost 6 years
    onDelete(name) { console.log("ProductList.onDelete: ", name); let {products} = this.state; products = products.filter(product => product.name !== name); this.setState({products}); localStorage.removeItem('products', JSON.stringify(products)); }
  • Prometheus
    Prometheus almost 6 years
    Yes, but i think if you need to remove an item from an array that you have to put in some key value as well or split the array.
  • Abhishek Konnur
    Abhishek Konnur almost 6 years
    products.filter(product => product.name !== name); is this line finding the item by name
  • Prometheus
    Prometheus almost 6 years
    You don't really use localStorage for arrays. Check out the map function in react if you really want to do things like this. You don't have any 'id' with localStorage, you can simply delete things via calling the exact name of the localStorage Item. If you have an item called (hello), well it will be deleted. But if you have 10 Items that are called "hello", all 10 of them will be deleted via localStorage.removeItem, simply because you don't have any id's attached to them. Your products need to be an array in order to do this. Again, check out the map function of react.
  • Sagar Gangwal
    Sagar Gangwal almost 4 years
    Provide explanation