Add state persistance function
This commit is contained in:
36
src/components/main/lib/state.ts
Normal file
36
src/components/main/lib/state.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { modifyPath, mergeDeepRight } from "ramda";
|
||||
|
||||
const STORAGE_KEY = "ecoplanet";
|
||||
|
||||
const defaultState = {
|
||||
dateCache: undefined,
|
||||
options: {
|
||||
lineWidth: undefined,
|
||||
defaultDate: undefined,
|
||||
},
|
||||
};
|
||||
|
||||
const stringifyState = function (state) {
|
||||
return JSON.stringify(state);
|
||||
};
|
||||
|
||||
const parseState = function (jsonString) {
|
||||
const state = JSON.parse(jsonString);
|
||||
return modifyPath(["options", "defaultDate"], Date.parse, state);
|
||||
};
|
||||
|
||||
export const persistStorage = function (state) {
|
||||
localStorage.setItem(STORAGE_KEY, stringifyState(state));
|
||||
};
|
||||
|
||||
export const loadStorage = function () {
|
||||
const storageStateString = localStorage.getItem(STORAGE_KEY);
|
||||
|
||||
if (storageStateString) {
|
||||
return parseState(storageStateString);
|
||||
}
|
||||
};
|
||||
|
||||
export const loadStorageOrDefault = function (state) {
|
||||
return mergeDeepRight(loadStorage(), defaultState);
|
||||
};
|
||||
Reference in New Issue
Block a user