From 0f6ad1a978377637003156c51a27b95eaf341635 Mon Sep 17 00:00:00 2001 From: David Date: Sat, 4 Sep 2021 18:58:26 +0200 Subject: [PATCH] Make localStorage usable while disabling cookies (#44) --- components/AutoTranslateButton.tsx | 5 +++-- utils/storage.ts | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 utils/storage.ts diff --git a/components/AutoTranslateButton.tsx b/components/AutoTranslateButton.tsx index 06475c9..19b76d0 100644 --- a/components/AutoTranslateButton.tsx +++ b/components/AutoTranslateButton.tsx @@ -1,6 +1,7 @@ import { useState, useEffect, FC } from "react"; import { IconButton } from "@chakra-ui/react"; import { FaBolt } from "react-icons/fa"; +import { localGetItem, localSetItem } from "@utils/storage"; type Props = { onAuto: () => void, @@ -8,7 +9,7 @@ type Props = { }; const initLocalStorage = () => { - const initial = typeof window !== "undefined" && localStorage.getItem("isauto"); + const initial = localGetItem("isauto"); return initial ? initial === "true" : false; }; @@ -16,7 +17,7 @@ const AutoTranslateButton: FC = ({ onAuto, ...props }) => { const [isAuto, setIsAuto] = useState(initLocalStorage); useEffect(() => { - localStorage.setItem("isauto", isAuto.toString()); + localSetItem("isauto", isAuto.toString()); }, [isAuto]); useEffect(() => { diff --git a/utils/storage.ts b/utils/storage.ts new file mode 100644 index 0000000..11dcd4b --- /dev/null +++ b/utils/storage.ts @@ -0,0 +1,15 @@ +// LocalStorage throws an error if all browser cookies are disabled + +export function localGetItem(key: string) { + try { + return localStorage.getItem(key); + } catch (e) { + return null; + } +} + +export function localSetItem(key: string, value: string) { + try { + localStorage.setItem(key, value); + } catch (e) { } +}