aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Utility/persistentStore.ts
blob: b08c825c8c3e9b0f5727b7a0868e774aeefa847e (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;
};