fix: fix app crash

this commit fixes a crash due to unavailability of localStorage

https://github.com/zyachel/libremdb/issues/31
This commit is contained in:
zyachel 2023-01-22 21:13:09 +05:30
parent feffb7d8f6
commit 71d1d5b34e
3 changed files with 24 additions and 3 deletions

View file

@ -1,10 +1,13 @@
import React, { useState, createContext, ReactNode } from 'react'; import React, { useState, createContext, ReactNode } from 'react';
import { isLocalStorageAvailable } from '../utils/helpers';
const getInitialTheme = () => { const getInitialTheme = () => {
// for server-side rendering, as window isn't availabe there // for server-side rendering, as window isn't availabe there
if (typeof window === 'undefined') return 'light'; if (typeof window === 'undefined') return 'light';
const userPrefersTheme = window.localStorage.getItem('theme') || null; const userPrefersTheme = isLocalStorageAvailable()
? window.localStorage.getItem('theme')
: null;
const browserPrefersDarkTheme = window.matchMedia( const browserPrefersDarkTheme = window.matchMedia(
'(prefers-color-scheme: dark)' '(prefers-color-scheme: dark)'
).matches; ).matches;
@ -35,7 +38,7 @@ const ThemeProvider = ({ children }: { children: ReactNode }) => {
const setTheme = (theme: string) => { const setTheme = (theme: string) => {
setCurTheme(theme); setCurTheme(theme);
window.localStorage.setItem('theme', theme); if (isLocalStorageAvailable()) window.localStorage.setItem('theme', theme);
document.documentElement.dataset.theme = theme; document.documentElement.dataset.theme = theme;
updateMetaTheme(); updateMetaTheme();
}; };

View file

@ -5,9 +5,17 @@ import Document, { Html, Head, Main, NextScript } from 'next/document';
const setInitialTheme = ` const setInitialTheme = `
(() => { (() => {
document.documentElement.dataset.js = true; document.documentElement.dataset.js = true;
const isLocalStorageAvailable = () => {
try {
window.localStorage.getItem('test');
return true;
} catch (e) {
return false;
}
}
let theme = 'light'; let theme = 'light';
let themeColor = '#ffe5ef'; let themeColor = '#ffe5ef';
const userPrefersTheme = window.localStorage.getItem('theme') || null; const userPrefersTheme = isLocalStorageAvailable() ? window.localStorage.getItem('theme') : null;
const browserPrefersDarkTheme = window.matchMedia('(prefers-color-scheme: dark)').matches; const browserPrefersDarkTheme = window.matchMedia('(prefers-color-scheme: dark)').matches;
if (userPrefersTheme) theme = userPrefersTheme; if (userPrefersTheme) theme = userPrefersTheme;
else if (browserPrefersDarkTheme) theme = 'dark'; else if (browserPrefersDarkTheme) theme = 'dark';

View file

@ -103,3 +103,13 @@ export const getResTitleTypeHeading = (
if (el.id === titleType) return el.name; if (el.id === titleType) return el.name;
} }
}; };
export const isLocalStorageAvailable = () => {
try {
localStorage.getItem('test');
return true;
} catch (e) {
return false;
}
};