diff --git a/src/contexts/AppLayoutContext.tsx b/src/contexts/AppLayoutContext.tsx index e45cc5f..74401e5 100644 --- a/src/contexts/AppLayoutContext.tsx +++ b/src/contexts/AppLayoutContext.tsx @@ -1,3 +1,4 @@ +import useStateWithLocalStorage from "hooks/useStateWithLocalStorage"; import React, { ReactNode, useContext, useEffect, useState } from "react"; export interface AppLayoutState { @@ -39,44 +40,32 @@ type Props = { }; export const AppContextProvider = (props: Props) => { - function useLocalStorage( - value: boolean, - setter: React.Dispatch>, - name: string - ): void { - useEffect(() => { - const data = localStorage.getItem(name); - if (data) setter(JSON.parse(data)); - }, [setter, name]); - - useEffect(() => { - localStorage.setItem(name, JSON.stringify(value)); - }, [value, name]); - } - - const [subPanelOpen, setSubPanelOpen] = useState( + const [subPanelOpen, setSubPanelOpen] = useStateWithLocalStorage( + "subPanelOpen", initialState.subPanelOpen ); - const [languagePanelOpen, setLanguagePanelOpen] = useState( - initialState.languagePanelOpen - ); + const [languagePanelOpen, setLanguagePanelOpen] = + useStateWithLocalStorage( + "languagePanelOpen", + initialState.languagePanelOpen + ); - const [mainPanelReduced, setMainPanelReduced] = useState( - initialState.mainPanelReduced - ); + const [mainPanelReduced, setMainPanelReduced] = + useStateWithLocalStorage( + "mainPanelReduced", + initialState.mainPanelReduced + ); - const [mainPanelOpen, setMainPanelOpen] = useState( + const [mainPanelOpen, setMainPanelOpen] = useStateWithLocalStorage( + "mainPanelOpen", initialState.mainPanelOpen ); - const [darkMode, setDarkMode] = useState(initialState.darkMode); - - useLocalStorage(subPanelOpen, setSubPanelOpen, "subPanelOpen"); - useLocalStorage(languagePanelOpen, setLanguagePanelOpen, "languagePanelOpen"); - useLocalStorage(mainPanelReduced, setMainPanelReduced, "mainPanelReduced"); - useLocalStorage(mainPanelOpen, setMainPanelOpen, "mainPanelOpen"); - useLocalStorage(darkMode, setDarkMode, "darkMode"); + const [darkMode, setDarkMode] = useStateWithLocalStorage( + "darkMode", + initialState.darkMode + ); return ( ( + key: string, + initialValue: T +): [T, React.Dispatch>] { + const [value, setValue] = useState(initialValue); + + useEffect(() => { + try { + const item = localStorage.getItem(key); + if (item) setValue(JSON.parse(item) as T); + } catch (error) { + console.warn(`Error reading localStorage key “${key}”:`, error); + } + }, [setValue, key]); + + useEffect(() => { + localStorage.setItem(key, JSON.stringify(value)); + }, [value, key]); + + return [value, setValue]; +}