Files
pezkuwi-telemetry/packages/frontend/src/persist/Persistent.ts
T
YJ 8e16f7c129 Unit testing Connections.ts (#66)
* Jest, Enzyme test env setup

* unit tests for telemetry state update logic

* remove sinon, superfluous scripts

* Remove console log
2018-10-05 09:14:53 +02:00

43 lines
1.0 KiB
TypeScript

import { Maybe, Stringified, stringify, parse } from '@dotstats/common';
export class Persistent<Data> {
private readonly onChange: (value: Data) => void;
private readonly key: string;
private value: Data;
constructor(key: string, initial: Data, onChange: (value: Readonly<Data>) => void) {
this.key = key;
this.onChange = onChange;
const stored = window.localStorage.getItem(key) as Maybe<Stringified<Data>>;
if (stored) {
try {
this.value = parse(stored);
} catch (err) {
this.value = initial;
}
} else {
this.value = initial;
}
window.addEventListener('storage', (event) => {
if (event.key === this.key) {
this.value = parse(event.newValue as any as Stringified<Data>);
this.onChange(this.value);
}
});
}
public get(): Readonly<Data> {
return this.value;
}
public set(value: Data) {
this.value = value;
window.localStorage.setItem(this.key, stringify(this.value) as any as string);
this.onChange(this.value);
}
}