From 82af2c6c63ec32ace9d82d996d3208716167ce59 Mon Sep 17 00:00:00 2001 From: Justin Campbell Date: Mon, 2 Aug 2021 17:02:03 -0400 Subject: [PATCH 1/2] Add useStickyState hook to utilities --- src/utilities.js | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) 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 From 905f656a3f9163df78be89602db25674b0c382a9 Mon Sep 17 00:00:00 2001 From: Justin Campbell Date: Mon, 2 Aug 2021 17:02:42 -0400 Subject: [PATCH 2/2] Replace darkMode state w/ new useStickyState hook --- src/App.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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() { - + ); }