简体   繁体   中英

storage eventlistener not working alongside any update to localstorage

In my componentDidMount I am trying to remove a localstorage item and also adding an event listener for further changes in the localstorage and it is not working

  componentDidMount() {
    localStorage.removeItem("receivedLocation");
    window.addEventListener("storage", event => {
      console.log("Event listener triggered");
      if (event.key === "receivedLocation" && event.newValue === true) {
        this.setState({
          receivedLocation: true
        });
      }
    });
  }

Whereas if I remove the update item it works fine.

  componentDidMount() {
    window.addEventListener("storage", event => {
      console.log("Event listener triggered");
      if (event.key === "receivedLocation" && event.newValue === true) {
        this.setState({
          receivedLocation: true
        });
      }
    });
  }

I am unable to reset the localstorage and also listen to future changes in the localstorage

The storage events do not fire in the current document . It is used to notify the other open tabs of your app of some change.

The storage event of the Window interface fires when a storage area (localStorage or sessionStorage) has been modified in the context of another document

If you are trying to notify other components in the current tab, you can use the DOMEvents for that.

const event = new Event('EVENT_NAME', { detail: { yourPayload }});
window.dispatchEvent(event);

// in your component
window.addEventListener('EVENT_NAME', configChangedHandler, false);

// cleanup
window.removeEventListener('EVENT_NAME', configChangedHandler);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM