From 7c7fb4903b9f09da5526611984e9252942cbc71a Mon Sep 17 00:00:00 2001 From: Lipis Date: Fri, 11 Dec 2020 18:13:13 +0200 Subject: [PATCH] Don't throw error when localStorage is null (#2505) --- src/excalidraw-app/data/localStorage.ts | 32 +++++++++++++++++-------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/excalidraw-app/data/localStorage.ts b/src/excalidraw-app/data/localStorage.ts index c9f4dc0d..2920b47b 100644 --- a/src/excalidraw-app/data/localStorage.ts +++ b/src/excalidraw-app/data/localStorage.ts @@ -99,19 +99,31 @@ export const importFromLocalStorage = () => { }; export const getElementsStorageSize = () => { - const elements = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_ELEMENTS); - const elementsSize = elements ? JSON.stringify(elements).length : 0; - return elementsSize; + try { + const elements = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_ELEMENTS); + const elementsSize = elements ? JSON.stringify(elements).length : 0; + return elementsSize; + } catch (error) { + console.error(error); + return 0; + } }; export const getTotalStorageSize = () => { - const appState = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_APP_STATE); - const collab = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_COLLAB); - const library = localStorage.getItem(APP_STORAGE_KEYS.LOCAL_STORAGE_LIBRARY); + try { + const appState = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_APP_STATE); + const collab = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_COLLAB); + const library = localStorage.getItem( + APP_STORAGE_KEYS.LOCAL_STORAGE_LIBRARY, + ); - const appStateSize = appState ? JSON.stringify(appState).length : 0; - const collabSize = collab ? JSON.stringify(collab).length : 0; - const librarySize = library ? JSON.stringify(library).length : 0; + const appStateSize = appState ? JSON.stringify(appState).length : 0; + const collabSize = collab ? JSON.stringify(collab).length : 0; + const librarySize = library ? JSON.stringify(library).length : 0; - return appStateSize + collabSize + librarySize + getElementsStorageSize(); + return appStateSize + collabSize + librarySize + getElementsStorageSize(); + } catch (error) { + console.error(error); + return 0; + } };