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
This commit is contained in:
schroda
2024-04-16 02:45:25 +02:00
parent 1352f636ba
commit 80ad5e06be

View File

@@ -26,15 +26,12 @@ export class Storage {
return this.parseValue(this.getItem(key), defaultValue); return this.parseValue(this.getItem(key), defaultValue);
} }
setItem(key: string, value: unknown): void { setItem(key: string, value: unknown, emitEvent: boolean = true): void {
if (value === undefined) { const fireEvent = (valueToStore: string | undefined) => {
this.storage.removeItem(key); if (!emitEvent) {
return; return;
} }
const valueToStore = JSON.stringify(value);
this.storage.setItem(key, valueToStore);
window.dispatchEvent( window.dispatchEvent(
new StorageEvent('storage', { new StorageEvent('storage', {
key, key,
@@ -42,6 +39,18 @@ export class Storage {
newValue: valueToStore, newValue: valueToStore,
}), }),
); );
};
if (value === undefined) {
this.storage.removeItem(key);
fireEvent(undefined);
return;
}
const valueToStore = JSON.stringify(value);
this.storage.setItem(key, valueToStore);
fireEvent(valueToStore);
} }
} }