diff --git a/src/App.js b/src/App.js index c410707..eff7deb 100644 --- a/src/App.js +++ b/src/App.js @@ -5,9 +5,10 @@ import { Switch, Route } from "react-router-dom"; import PrivateRoute from "./components/PrivateRoute/"; import AppView from "./components/AppView/"; import LoginForm from "./components/LoginForm/"; +import { useStickyState } from "./utilities"; function App() { - const [darkMode, setDarkMode] = useState(false); + const [darkMode, setDarkMode] = useStickyState(false); const theme = webqueueTheme(darkMode); @@ -20,7 +21,7 @@ function App() { - + ); } diff --git a/src/utilities.js b/src/utilities.js index 550f6ff..c9685f9 100644 --- a/src/utilities.js +++ b/src/utilities.js @@ -1,3 +1,5 @@ +import { useState, useEffect } from "react"; + /** * Returns true if object has no entries, otherwise false. * @param {Object} objectToCheck The object to check. @@ -7,4 +9,24 @@ function objectIsEmpty(objectToCheck) { return Object.entries(objectToCheck).length === 0; } -export { objectIsEmpty }; \ No newline at end of file +/** + * Returns value of key in localStorage or default value in state. The state and localStorage value are updated together. + * @param {*} defaultValue The value to use if no value for key exist in localStorage. + * @param {string} key The key to lookup in localStorage. + * @returns {Array} Getter and setter of state variable. + * @see https://reactjs.org/docs/hooks-state.html + */ +function useStickyState(defaultValue, key) { + const [value, setValue] = useState(() => { + const stickyValue = window.localStorage.getItem(key); + return stickyValue !== null + ? JSON.parse(stickyValue) + : defaultValue; + }); + useEffect(() => { + window.localStorage.setItem(key, JSON.stringify(value)); + }, [key, value]); + return [value, setValue]; +} + +export { objectIsEmpty, useStickyState }; \ No newline at end of file