aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Utility/persistentStore.ts
blob: 7df3049fb0c975dea2ef092c2c118c838c1a322b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { writable, type Writable } from "svelte/store";
import { browser } from "$app/environment";

export const persistentStore = <T>(key: string, initial: T): Writable<T> => {
	const store = writable<T>(initial);

	if (browser)
		import("localforage").then((localforage) => {
			localforage.default.getItem<T>(key).then((value) => {
				if (value !== null) store.set(value);
			});

			store.subscribe((value) => {
				localforage.default.setItem(key, value);
			});
		});

	return store;
};