From 80ad5e06be4070674699ff4889753bd4c8fa717b Mon Sep 17 00:00:00 2001 From: schroda <50052685+schroda@users.noreply.github.com> Date: Tue, 16 Apr 2024 02:45:25 +0200 Subject: [PATCH] Optionally don't fire storage event In case a value should be updated without informing subscribes about the change. E.g. to prevent unnecessary re-renders when using a storage hook --- src/util/AppStorage.ts | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/util/AppStorage.ts b/src/util/AppStorage.ts index 0e458d01..52eb51c3 100644 --- a/src/util/AppStorage.ts +++ b/src/util/AppStorage.ts @@ -26,22 +26,31 @@ export class Storage { return this.parseValue(this.getItem(key), defaultValue); } - setItem(key: string, value: unknown): void { + setItem(key: string, value: unknown, emitEvent: boolean = true): void { + const fireEvent = (valueToStore: string | undefined) => { + if (!emitEvent) { + return; + } + + window.dispatchEvent( + new StorageEvent('storage', { + key, + oldValue: this.getItem(key), + newValue: valueToStore, + }), + ); + }; + if (value === undefined) { this.storage.removeItem(key); + fireEvent(undefined); return; } const valueToStore = JSON.stringify(value); this.storage.setItem(key, valueToStore); - window.dispatchEvent( - new StorageEvent('storage', { - key, - oldValue: this.getItem(key), - newValue: valueToStore, - }), - ); + fireEvent(valueToStore); } }