diff --git a/.changeset/wicked-vans-build.md b/.changeset/wicked-vans-build.md new file mode 100644 index 00000000..7a86998d --- /dev/null +++ b/.changeset/wicked-vans-build.md @@ -0,0 +1,5 @@ +--- +"runed": minor +--- + +PersistedState: add `reset` to remove persisted state from storage diff --git a/packages/runed/src/lib/utilities/persisted-state/persisted-state.svelte.ts b/packages/runed/src/lib/utilities/persisted-state/persisted-state.svelte.ts index 70a8fa45..811d6d75 100644 --- a/packages/runed/src/lib/utilities/persisted-state/persisted-state.svelte.ts +++ b/packages/runed/src/lib/utilities/persisted-state/persisted-state.svelte.ts @@ -74,7 +74,7 @@ export class PersistedState { #update: VoidFunction | undefined; #proxies = new WeakMap(); - constructor(key: string, initialValue: T, options: PersistedStateOptions = {}) { + constructor(key: string, initialValue: T | null, options: PersistedStateOptions = {}) { const { storage: storageType = "local", serializer = { serialize: JSON.stringify, deserialize: JSON.parse }, @@ -94,7 +94,7 @@ export class PersistedState { const existingValue = storage.getItem(key); if (existingValue !== null) { this.#current = this.#deserialize(existingValue); - } else { + } else if (initialValue !== null) { this.#serialize(initialValue); } @@ -131,8 +131,12 @@ export class PersistedState { } #handleStorageEvent = (event: StorageEvent): void => { - if (event.key !== this.#key || event.newValue === null) return; - this.#current = this.#deserialize(event.newValue); + if (event.key !== this.#key) return; + if (event.newValue === null) { + this.#current = null; + } else { + this.#current = this.#deserialize(event.newValue); + } this.#update?.(); }; @@ -157,4 +161,10 @@ export class PersistedState { ); } } + + remove(): void { + this.#storage?.removeItem(this.#key); + this.#current = null; + this.#update?.(); + } }