Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(persisted-state): write state to storage even if only a nested property is changed. fixes #224 #225

Merged
merged 2 commits into from
Mar 17, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { createSubscriber } from "svelte/reactivity";

type Serializer<T> = {
serialize: (value: T) => string;
deserialize: (value: string) => T;
deserialize: (value: string) => T | undefined;
};

type StorageType = "local" | "session";
Expand Down Expand Up @@ -36,11 +36,12 @@ type PersistedStateOptions<T> = {
* @see {@link https://runed.dev/docs/utilities/persisted-state}
*/
export class PersistedState<T> {
#current: T = $state()!;
#current: T | undefined;
#key: string;
#serializer: Serializer<T>;
#storage?: Storage;
#subscribe?: VoidFunction;
#version = $state(0)

constructor(key: string, initialValue: T, options: PersistedStateOptions<T> = {}) {
const {
Expand All @@ -61,7 +62,9 @@ export class PersistedState<T> {

const existingValue = storage.getItem(key);
if (existingValue !== null) {
this.#deserialize(existingValue);
this.#current = this.#deserialize(existingValue);
} else {
this.#serialize(initialValue)
}

if (syncTabs && storageType === "local") {
Expand All @@ -73,36 +76,62 @@ export class PersistedState<T> {

get current(): T {
this.#subscribe?.();
return this.#current;
const root = this.#deserialize(this.#storage?.getItem(this.#key) as string) ?? this.#current
const proxies = new WeakMap();
const proxy = (value: unknown) => {
if (value === null || value?.constructor.name === 'Date' || typeof value !== 'object') {
return value;
}
let p = proxies.get(value);
if (!p) {
p = new Proxy(value, {
get: (target, property) => {
this.#version;
return proxy(Reflect.get(target, property));
},
set: (target, property, value) => {
this.#version += 1;
Reflect.set(target, property, value);
this.#serialize(root)
return true;
}
});
proxies.set(value, p);
}
return p;
}
return proxy(root);
}

set current(newValue: T) {
this.#current = newValue;
this.#serialize(newValue);
this.#version += 1;
}

#handleStorageEvent = (event: StorageEvent): void => {
if (event.key !== this.#key || event.newValue === null) return;

this.#deserialize(event.newValue);
this.#current = this.#deserialize(event.newValue);
};

#deserialize(value: string): void {
#deserialize(value: string): T | undefined {
try {
this.#current = this.#serializer.deserialize(value);
return this.#serializer.deserialize(value);
} catch (error) {
console.error(`Error when parsing "${value}" from persisted store "${this.#key}"`, error);
return
}
}

#serialize(value: T): void {
#serialize(value: T | undefined): void {
try {
this.#storage?.setItem(this.#key, this.#serializer.serialize(value));
if (value != undefined) {
this.#storage?.setItem(this.#key, this.#serializer.serialize(value));
}
} catch (error) {
console.error(
`Error when writing value from persisted store "${this.#key}" to ${this.#storage}`,
error
);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,31 @@ describe("PersistedState", () => {
expect(persistedState.current).toBe(newValue);
expect(localStorage.getItem(key)).toBe(JSON.stringify(newValue));
});

testWithEffect("updates localStorage when a nested property in current value changes", () => {
const propValue = "test"
const initialValue = { prop: { nested: propValue } };
const newPropValue = "new test"
const newValue = { prop: { nested: newPropValue } };
const persistedState = new PersistedState(key, initialValue);
expect(persistedState.current).toEqual(initialValue);

persistedState.current.prop.nested = newPropValue;
expect(persistedState.current).toEqual(newValue);
expect(localStorage.getItem(key)).toBe(JSON.stringify(newValue));
});

testWithEffect("updates current value when localStorage changes", () => {
const propValue = "test"
const initialValue = { prop: { nested: propValue } };
const newPropValue = "new test"
const newValue = { prop: { nested: newPropValue } };
const persistedState = new PersistedState(key, initialValue);
expect(persistedState.current).toEqual(initialValue);
localStorage.setItem(key, JSON.stringify(newValue))
expect(persistedState.current).toEqual(newValue);
});

});

describe("sessionStorage", () => {
Expand Down Expand Up @@ -73,7 +98,7 @@ describe("PersistedState", () => {
const iso2024FebFirst = "2024-02-01T00:00:00.000Z";
const date2024FebFirst = new Date(iso2024FebFirst);
persistedState.current = date2024FebFirst;
expect(persistedState.current).toBe(date2024FebFirst);
expect(persistedState.current).toEqual(date2024FebFirst);
expect(localStorage.getItem(key)).toBe(iso2024FebFirst);
});
});
Expand Down