-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
40 lines (30 loc) · 851 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { writable } from 'svelte/store';
let prefix = 'svelteStore';
const get = (key) => {
if (typeof window === 'undefined' || !window.localStorage) return;
const value = localStorage.getItem(key);
return value === undefined
? ""
: JSON.parse(value);
};
const set = (key, value) => {
if (typeof window === 'undefined' || !window.localStorage) return;
localStorage.setItem(key, JSON.stringify(value));
};
const syncValue = (key, observable) => {
observable.subscribe(data => {
set(key, data);
});
return observable;
};
export const setPrefix = (prefixName) => {
prefix = prefixName;
};
export const syncable = (name, value, hydrate = true) => {
const key = `${prefix}-${name}`;
let lastValue = value;
if (hydrate) {
lastValue = get(key) || value;
}
return syncValue(key, writable(lastValue));
};