DEV Community

Vinay Veerappaji
Vinay Veerappaji

Posted on

Reload other tabs with a value change in current tab

Have you ever faced the need to reload multiple tabs of your web application after a user changes some settings, like switching their account? One solution to this problem is to use the localStorage API to communicate changes across multiple tabs.

I will explain how to do this in a react application. I'll be explaining in class based component so it will be easily understood.

Let's consider an example where User is switching his profile, and considering accountID is the unique value which changes on account/profile switch and we will store that in local storage of the browser.

Using the Storage Event
The storage event is fired on the window object when a key in the localStorage object is updated. You can use it to detect changes in the values stored in localStorage and perform any necessary updates in your application.

const accountID = "abc" // getting a new unique account ID
localStorage.setItem('accountID', accountID);
Enter fullscreen mode Exit fullscreen mode

Window: storage event

The **storage event **is fired on all window objects (i.e., all open tabs), but we only want to handle changes made in the current tab.

class MyComponent extends React.Component {
  componentDidMount() {
    window.addEventListener('storage', this.handleStorageChange);
  }

  componentWillUnmount() {
    window.removeEventListener('storage', this.handleStorageChange);
  }

  handleStorageChange = e => {
    if (e.storageArea != localStorage) {
      return;
    }
    if (e.key === 'accountID') {
      // Reload all other tabs here
    }
  }

  render() {
    // Your component's rendering logic here
  }
}
Enter fullscreen mode Exit fullscreen mode

The Reload logic is given below:

Either you can reload the same page

window.location.reload();

or you can load them back to home page of your app
window.location.replace(window.siteURL);

That's all folks you can achieve by doing go. You can replicate the same logic in function based component also.

Top comments (0)