We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 34065cf commit 84cf26aCopy full SHA for 84cf26a
1 file changed
src/lib/stores/LocalStorageState.svelte.ts
@@ -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