Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How can I use the "storage" event to sync data between tabs
    storage event sync data between tabs local storage JavaScript web development data synchronization browser tabs React hook web storage


How can I use the "storage" event to sync data between tabs


To use the "storage" event to sync data between tabs, you can follow these steps:

Step 1: Set Up Event Listener

1. Add Event Listener: Attach an event listener to the window object to listen for changes in local storage. This will allow you to detect when data is updated in one tab and sync it across all other tabs.

javascript
window.addEventListener('storage', function(event) {
  if (event.key === 'your-key') {
    // Update UI with new data
  }
});

Step 2: Store Data

2. Store Data: Store the data you want to sync in local storage. This can be done using the `localStorage.setItem()` method.

javascript
localStorage.setItem('your-key', JSON.stringify(data));

Step 3: Fetch and Update Data

3. Fetch and Update Data: When the event listener detects a change in local storage, fetch the new data and update the UI accordingly.

javascript
function checkAndRefreshLocalStorage() {
  const storageKey = 'your-key';
  const now = new Date().getTime();
  const storedData = localStorage.getItem(storageKey);

  if (storedData) {
    const storedDataObject = JSON.parse(storedData);
    const expirationDate = new Date(storedDataObject.timestamp).getTime();

    if (now > expirationDate) {
      // Data has expired, fetch new data and update local storage
      fetchAndStoreNewData(storageKey);
    } else {
      // Data is still valid, return the stored data
      return storedDataObject.data;
    }
  } else {
    // No data in local storage, fetch new data and store it
    fetchAndStoreNewData(storageKey);
  }
}

// Example usage
const data = checkAndRefreshLocalStorage();
if (data) {
  // Use the retrieved data
  console.log(data);
} else {
  // Data was refreshed, use the new data
  console.log(fetchAndStoreNewData('your-key'));
}

Step 4: Handle Data Updates

4. Handle Data Updates: When the data is updated in one tab, ensure that all other tabs are notified and updated accordingly.

javascript
function fetchAndStoreNewData(key) {
  // Fetch new data from your API or other source
  const newData = fetchDataFromSource();

  // Store the new data in local storage with a timestamp
  const dataObject = {
    timestamp: new Date().getTime(),
    data: newData
  };
  localStorage.setItem(key, JSON.stringify(dataObject));

  return newData;
}

Example Usage

javascript
// Example usage
const data = checkAndRefreshLocalStorage();
if (data) {
  // Use the retrieved data
  console.log(data);
} else {
  // Data was refreshed, use the new data
  console.log(fetchAndStoreNewData('your-key'));
}

Best Practices

- Use a custom React hook: Extract the storage functionality into a reusable custom React hook to simplify usage across multiple components.
- Clear unnecessary data: Ensure to clear unnecessary data from local storage to maintain privacy and free up storage space.

By following these steps and best practices, you can effectively use the "storage" event to sync data between tabs and ensure that your application remains up-to-date across all open tabs.

Citations:
[1] https://www.youtube.com/watch?v=82EGTEqxiNA
[2] https://torsten-muller.dev/javascript/communication-between-browser-tabs-synchronizing-state/
[3] https://dev.to/cassiolacerda/how-to-syncing-react-state-across-multiple-tabs-with-usestate-hook-4bdm
[4] https://stackoverflow.com/questions/44438393/javascript-tabs-synchronization-and-server-events
[5] https://nabeelvalley.co.za/blog/2024/07-03/localstorage-based-sync/