Skip to content

Commit 84cf26a

Browse files
committed
Create LocalStorageState.svelte.ts
1 parent 34065cf commit 84cf26a

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { browser } from '$app/environment';
2+
3+
export class LocaleStorageState<T> {
4+
#key: string;
5+
#default: T;
6+
#value: T;
7+
8+
constructor(key: string, defaultValue: T) {
9+
this.#key = key;
10+
this.#default = defaultValue;
11+
12+
const existingValue = browser ? localStorage.getItem(key) : null;
13+
this.#value = $state<T>(
14+
existingValue === null ? defaultValue : (JSON.parse(existingValue) as T)
15+
);
16+
}
17+
18+
get Value() {
19+
return this.#value;
20+
}
21+
set Value(value: T) {
22+
this.#value = value;
23+
localStorage.setItem(this.#key, JSON.stringify(value));
24+
}
25+
26+
Reset() {
27+
this.#value = this.#default;
28+
localStorage.removeItem(this.#key);
29+
}
30+
}

0 commit comments

Comments
 (0)