Skip to content

Commit

Permalink
Merge pull request #228 from ECN/feature-store-darkmode-preference
Browse files Browse the repository at this point in the history
Store dark mode preference in localStorage
  • Loading branch information
campb303 authored Aug 2, 2021
2 parents 85f262d + 905f656 commit 8d2a727
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
5 changes: 3 additions & 2 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -20,7 +21,7 @@ function App() {
<PrivateRoute path="/">
<AppView setDarkMode={setDarkMode} />
</PrivateRoute>
</Switch>
</Switch>
</ThemeProvider>
);
}
Expand Down
24 changes: 23 additions & 1 deletion src/utilities.js
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -7,4 +9,24 @@ function objectIsEmpty(objectToCheck) {
return Object.entries(objectToCheck).length === 0;
}

export { objectIsEmpty };
/**
* 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 };

0 comments on commit 8d2a727

Please sign in to comment.