gd vigneshwar
gd vigneshwar

Reputation: 867

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

Upvotes: 0

Views: 1194

Answers (1)

Incepter
Incepter

Reputation: 2948

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);

Upvotes: 1

Related Questions