Make localStorage usable while disabling cookies (#44)
This commit is contained in:
@@ -1,6 +1,7 @@
|
|||||||
import { useState, useEffect, FC } from "react";
|
import { useState, useEffect, FC } from "react";
|
||||||
import { IconButton } from "@chakra-ui/react";
|
import { IconButton } from "@chakra-ui/react";
|
||||||
import { FaBolt } from "react-icons/fa";
|
import { FaBolt } from "react-icons/fa";
|
||||||
|
import { localGetItem, localSetItem } from "@utils/storage";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
onAuto: () => void,
|
onAuto: () => void,
|
||||||
@@ -8,7 +9,7 @@ type Props = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const initLocalStorage = () => {
|
const initLocalStorage = () => {
|
||||||
const initial = typeof window !== "undefined" && localStorage.getItem("isauto");
|
const initial = localGetItem("isauto");
|
||||||
return initial ? initial === "true" : false;
|
return initial ? initial === "true" : false;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -16,7 +17,7 @@ const AutoTranslateButton: FC<Props> = ({ onAuto, ...props }) => {
|
|||||||
const [isAuto, setIsAuto] = useState(initLocalStorage);
|
const [isAuto, setIsAuto] = useState(initLocalStorage);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
localStorage.setItem("isauto", isAuto.toString());
|
localSetItem("isauto", isAuto.toString());
|
||||||
}, [isAuto]);
|
}, [isAuto]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
15
utils/storage.ts
Normal file
15
utils/storage.ts
Normal file
@@ -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) { }
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user