Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove item from array using localStorage.removeItem?

I'm using localStorage.setItem and localStorage.getItem to store data (devices, in my case) from an API to persist through page resets. When a device is clicked on, it gets stored into a shopping bag. When the user clicks a device in the bag, I want it to be able to "delete" and be removed from the local storage. Right now it work so that on the UI it shows that it's being removed, but when the page refreshes it comes back because it's still in the localStorage.

I've tried to use localStorage.removeItem(deviceTitle) in my removeDevice function, but it doesn't seem to do anything. Is this because I have the localStorage.getItem in the componentDidMount? If so, how do I go about changing that so the removeItem function will work?

addDevice() is called during by onClick function (please let me know if you need to see that portion of the code)

  addDevice = (e, deviceTitle) => {
    const array = Array.from(this.state.bag);
    if (array.indexOf(deviceTitle) === -1) {
      array.push(deviceTitle);
    } else {
      return;
    }
    localStorage.setItem("list", JSON.stringify(array));
    this.setState({
      bag: array
    });
  };

Here is where the the device is supposed to be removed from local storage

removeDevice = (e, deviceTitle) => {
    this.setState(prevState => ({
      bag: prevState.bag.filter(d => d !== deviceTitle)
    }));
    localStorage.removeItem(deviceTitle);
  };

and this is my componentDidMount() where the devices get stored

componentDidMount() {
    this.search("");
    const storedList = JSON.parse(localStorage.getItem("list"));
    console.log(storedList);
    const bag = storedList;
    this.setState({ bag });
  }

EDIT more code added below:

  render() {
    return (
      <div>
        <form>
          <input
            type="text"
            placeholder="Search for devices..."
            onChange={this.onChange}
          />
          {this.state.devices.map(device => (
            <ul key={device.title}>
              <p>
                {device.title}{" "}
                <i
                  className="fas fa-plus"
                  style={{ cursor: "pointer", color: "green" }}
                  onClick={e => this.addDevice(e, device.title)}
                />
              </p>
            </ul>
          ))}
        </form>
        {this.state.bag.map(device => (
          <p key={device.title}>
            {device}
            <i
              className="fas fa-times"
              style={{ cursor: "pointer", color: "red" }}
              onClick={e => this.removeDevice(e, device)}
            />
          </p>
        ))}
        <button onClick={e => this.removeAll(e)}>Remove all</button>
      </div>
    );
  }
}

Here are screenshots of how it looks: items in local storage, items after being removed in the UI but when I reset the page, it reverts back to the first image because the devices weren't removed from localStorage

like image 375
Emily Avatar asked Jul 13 '26 01:07

Emily


1 Answers

Simply replace the array after removing the item itself

removeDevice = (e, deviceTitle) => {
    this.setState(prevState => ({
      bag: prevState.bag.filter(d => d !== deviceTitle)
    }));
    // actual localStorage item removing 
        let devicesArray  = JSON.parse(localStorage.getItem("list"))
        devicesArray.splice(devicesArray.indexOf(deviceTitle), 1)
        localStorage.setItem("list", JSON.stringify(devicesArray));
  };

because setting item if it's there it replace it's value check here

like image 196
mooga Avatar answered Jul 15 '26 13:07

mooga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!