Skip to content
Open
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions .changeset/wicked-vans-build.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"runed": minor
---

PersistedState: add `reset` to remove persisted state from storage
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export class PersistedState<T> {
#update: VoidFunction | undefined;
#proxies = new WeakMap();

constructor(key: string, initialValue: T, options: PersistedStateOptions<T> = {}) {
constructor(key: string, initialValue: T | null, options: PersistedStateOptions<T> = {}) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why should it be potentially null? Shouldn't that be a part of T?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The removeItem() method of the Storage interface sets the item to null when it's removed. So if the user chooses a null value it won't be saved to the local storage (this is just a work around).
The #current: T | undefined; is already typed as T | undefined i didn't want to use undefined and used null instead so it won't interfere with the current codebase.

const {
storage: storageType = "local",
serializer = { serialize: JSON.stringify, deserialize: JSON.parse },
Expand All @@ -94,7 +94,7 @@ export class PersistedState<T> {
const existingValue = storage.getItem(key);
if (existingValue !== null) {
this.#current = this.#deserialize(existingValue);
} else {
} else if (initialValue !== null) {
this.#serialize(initialValue);
}

Expand Down Expand Up @@ -131,8 +131,12 @@ export class PersistedState<T> {
}

#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?.();
};

Expand All @@ -157,4 +161,10 @@ export class PersistedState<T> {
);
}
}

remove(): void {
this.#storage?.removeItem(this.#key);
this.#current = null;
this.#update?.();
}
}