Home > Back-end >  Is there a way to toggle something out of localStorage?
Is there a way to toggle something out of localStorage?

Time:10-02

I want to have a button that toggles something in and out of localStorage (it's clicked once and it adds something to localStorage, it's clicked again and that something disappears from localStorage). I want to do something like the code below, but toggling "status" instead of setting it permanently.

  function setStatus(statusName) {
    localStorage.setItem('status', statusName);
    document.documentElement.className = statusName;
  }

  (function () {
    if (localStorage.getItem('status')) {
      setStatus(localStorage.getItem('status'))
    }

This is code that I've used in something unrelated, and I know that it works. However, this sets the status, it doesn't toggle it. I'm wondering if there's a way to revise that code so that it does.

CodePudding user response:

Maybe using Storage.removeItem()?

function toggleItem(item, value) {
  if (localStorage.getItem(item) {
    localStorage.removeItem(item);
  } else {
    localStorage.setItem(item, value);
  }
}

Does it satisfies your requirement?

  • Related