mapcomplete/Logic/Web/LocalStorageSource.ts

45 lines
1.3 KiB
TypeScript
Raw Normal View History

import {UIEventSource} from "../UIEventSource";
2021-03-29 14:10:20 +02:00
/**
* UIEventsource-wrapper around localStorage
*/
export class LocalStorageSource {
static GetParsed<T>(key: string, defaultValue: T): UIEventSource<T> {
return LocalStorageSource.Get(key).map(
str => {
if (str === undefined) {
return defaultValue
}
try {
return JSON.parse(str)
} catch {
return defaultValue
}
}, [],
value => JSON.stringify(value)
)
}
static Get(key: string, defaultValue: string = undefined): UIEventSource<string> {
2020-07-31 17:11:44 +02:00
try {
const saved = localStorage.getItem(key);
const source = new UIEventSource<string>(saved ?? defaultValue, "localstorage:" + key);
2020-07-31 17:11:44 +02:00
source.addCallback((data) => {
try {
2021-03-29 14:10:20 +02:00
localStorage.setItem(key, data);
} catch (e) {
2021-03-29 14:10:20 +02:00
// Probably exceeded the quota with this item!
// Lets nuke everything
localStorage.clear()
}
2020-07-31 17:11:44 +02:00
});
return source;
} catch (e) {
return new UIEventSource<string>(defaultValue);
}
}
2020-07-31 17:11:44 +02:00
}