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,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);
}
}