easyTechnical2024

Local storage storage sync events

3.2k views
01

Understand the problem

Implement the scenario utility: Local storage storage sync events. Discuss edge cases, runtime performance, and alternative paradigms.

js-codingutilityalgorithm
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Example usage
function onStorageChange(key, cb) {
  if (typeof window === 'undefined' || !window.addEventListener) {
    return () => {};
  }
  
  const listener = (e) => {
    // storage event fires on OTHER windows/tabs
    if (e.key === key && e.storageArea === localStorage) {
      cb(e.newValue, e.oldValue);
    }
  };
  
  window.addEventListener('storage', listener);
  
  // Custom hook for same-tab updates (since standard storage listener only fires cross-tab)
  const originalSetItem = localStorage.setItem;
  localStorage.setItem = function(k, v) {
    const oldValue = localStorage.getItem(k);
    originalSetItem.apply(this, arguments);
    if (k === key && oldValue !== v) {
      cb(v, oldValue);
    }
  };
  
  return () => {
    window.removeEventListener('storage', listener);
    localStorage.setItem = originalSetItem; // restore original hook
  };
}

// Example placeholder (requires browser environment)
// const cancel = onStorageChange('user-token', (newV, oldV) => console.log('token updated:', newV));
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.