use editor data optimalizactions

This commit is contained in:
Jan Prochazka
2020-12-03 17:24:37 +01:00
parent d23a013579
commit 5df650bc51
4 changed files with 70 additions and 75 deletions

View File

@@ -1,29 +1,44 @@
import React from 'react';
import _ from 'lodash';
import localforage from 'localforage';
import { changeTab } from './common';
import { useSetOpenedTabs } from './globalState';
export default function useEditorData(tabid, initialData = null) {
export default function useEditorData({ tabid, loadFromArgs }) {
const localStorageKey = `tabdata_${tabid}`;
const setOpenedTabs = useSetOpenedTabs();
const changeCounterRef = React.useRef(0);
const savedCounterRef = React.useRef(0);
const [value, setValue] = React.useState(initialData);
const [value, setValue] = React.useState(null);
const [isLoading, setIsLoading] = React.useState(true);
const valueRef = React.useRef(null);
const initialLoad = async () => {
const initFallback = localStorage.getItem(localStorageKey);
if (initFallback != null) {
const init = JSON.parse(initFallback);
if (loadFromArgs) {
const init = await loadFromArgs();
changeTab(tabid, setOpenedTabs, (tab) => ({
...tab,
props: _.omit(tab.props, ['initialArgs']),
}));
setValue(init);
valueRef.current = init;
// move to local forage
await localforage.setItem(localStorageKey, init);
localStorage.removeItem(localStorageKey);
} else {
const init = await localforage.getItem(localStorageKey);
if (init) {
const initFallback = localStorage.getItem(localStorageKey);
if (initFallback != null) {
const init = JSON.parse(initFallback);
setValue(init);
valueRef.current = init;
// move to local forage
await localforage.setItem(localStorageKey, init);
localStorage.removeItem(localStorageKey);
} else {
const init = await localforage.getItem(localStorageKey);
if (init) {
setValue(init);
valueRef.current = init;
}
}
}
setIsLoading(false);
@@ -37,6 +52,7 @@ export default function useEditorData(tabid, initialData = null) {
if (valueRef.current == null) return;
try {
await localforage.setItem(localStorageKey, valueRef.current);
savedCounterRef.current = changeCounterRef.current;
} catch (err) {
console.error(err);
}
@@ -44,6 +60,7 @@ export default function useEditorData(tabid, initialData = null) {
const saveToStorageFallback = React.useCallback(() => {
if (valueRef.current == null) return;
if (savedCounterRef.current == changeCounterRef.current) return; // all saved
// on window unload must be synchronous actions, save to local storage instead
localStorage.setItem(localStorageKey, JSON.stringify(valueRef.current));
}, [localStorageKey, valueRef]);
@@ -53,6 +70,7 @@ export default function useEditorData(tabid, initialData = null) {
const handleChange = (newValue) => {
if (newValue != null) valueRef.current = newValue;
setValue(newValue);
changeCounterRef.current += 1;
saveToStorageDebounced();
};