use editor data - sync fallback when called from beforeunload

This commit is contained in:
Jan Prochazka
2020-12-03 15:22:53 +01:00
parent fc5c0eb239
commit d23a013579

View File

@@ -11,11 +11,21 @@ export default function useEditorData(tabid, initialData = null) {
const valueRef = React.useRef(null); const valueRef = React.useRef(null);
const initialLoad = async () => { const initialLoad = async () => {
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); const init = await localforage.getItem(localStorageKey);
if (init) { if (init) {
setValue(init); setValue(init);
valueRef.current = init; valueRef.current = init;
} }
}
setIsLoading(false); setIsLoading(false);
}; };
@@ -32,7 +42,13 @@ export default function useEditorData(tabid, initialData = null) {
} }
}, [localStorageKey, valueRef]); }, [localStorageKey, valueRef]);
const saveToStorageDebounced = React.useMemo(() => _.debounce(saveToStorage, 500), [saveToStorage]); const saveToStorageFallback = React.useCallback(() => {
if (valueRef.current == null) return;
// on window unload must be synchronous actions, save to local storage instead
localStorage.setItem(localStorageKey, JSON.stringify(valueRef.current));
}, [localStorageKey, valueRef]);
const saveToStorageDebounced = React.useMemo(() => _.debounce(saveToStorage, 5000), [saveToStorage]);
const handleChange = (newValue) => { const handleChange = (newValue) => {
if (newValue != null) valueRef.current = newValue; if (newValue != null) valueRef.current = newValue;
@@ -41,10 +57,10 @@ export default function useEditorData(tabid, initialData = null) {
}; };
React.useEffect(() => { React.useEffect(() => {
window.addEventListener('beforeunload', saveToStorage); window.addEventListener('beforeunload', saveToStorageFallback);
return () => { return () => {
saveToStorage(); saveToStorage();
window.removeEventListener('beforeunload', saveToStorage); window.removeEventListener('beforeunload', saveToStorageFallback);
}; };
}, []); }, []);