Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion infrastructure/persistence/localStorageAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ const safeParse = <T>(value: string | null): T | null => {

export const LOCAL_STORAGE_ADAPTER_CHANGED_EVENT = 'netcatty:local-storage-adapter-changed';

function emitLocalStorageAdapterChanged(key: string): void {
const pendingChangedKeys = new Set<string>();
let emitChangedKeysTimer: ReturnType<typeof setTimeout> | null = null;

function dispatchLocalStorageAdapterChanged(key: string): void {
try {
const target = globalThis as typeof globalThis & {
dispatchEvent?: (event: Event) => boolean;
Expand All @@ -25,6 +28,22 @@ function emitLocalStorageAdapterChanged(key: string): void {
}
}

function emitLocalStorageAdapterChanged(key: string): void {
pendingChangedKeys.add(key);
if (emitChangedKeysTimer) return;

// Defer same-window storage notifications so React render-phase writes do
// not synchronously trigger state updates in unrelated components.
emitChangedKeysTimer = setTimeout(() => {
emitChangedKeysTimer = null;
const keys = Array.from(pendingChangedKeys);
pendingChangedKeys.clear();
for (const changedKey of keys) {
dispatchLocalStorageAdapterChanged(changedKey);
}
}, 0);
}

/**
* Safely write to localStorage, catching QuotaExceededError.
* Returns true if the write succeeded, false if storage quota was exceeded.
Expand Down
Loading