Skip to content

Store dark mode preference in localStorage #228

Merged
merged 2 commits into from
Aug 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 };