Skip to content

Commit

Permalink
feat: persist it also in local storage
Browse files Browse the repository at this point in the history
  • Loading branch information
TN1ck committed Sep 26, 2024
1 parent a516ec9 commit f4befe8
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions src/components/modules/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,18 +82,49 @@ const NewGameButton: React.FC<NewGamePropsFromRedux> = ({pauseGame, chooseGame})
const ConnectedNewGameButton = newGameConnector(NewGameButton);

const Header = () => {
const [darkMode, setDarkMode] = React.useState(false);
const [darkMode, setDarkMode] = React.useState(() => {
if (typeof window !== "undefined" && typeof localStorage !== "undefined") {
const savedMode = localStorage.getItem("darkMode");
if (savedMode !== null) {
return JSON.parse(savedMode);
}
return window.matchMedia("(prefers-color-scheme: dark)").matches;
}
return false;
});

React.useEffect(() => {
if (darkMode) {
document.body.classList.add("dark");
} else {
document.body.classList.remove("dark");
}
if (typeof localStorage !== "undefined") {
localStorage.setItem("darkMode", JSON.stringify(darkMode));
}
}, [darkMode]);

React.useEffect(() => {
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = (e: MediaQueryListEvent) => {
const newMode = e.matches;
setDarkMode(newMode);
if (typeof localStorage !== "undefined") {
localStorage.setItem("darkMode", JSON.stringify(newMode));
}
};
mediaQuery.addEventListener("change", handleChange);
return () => mediaQuery.removeEventListener("change", handleChange);
}, []);

const toggleDarkMode = () => {
setDarkMode((prevMode) => !prevMode);
setDarkMode((prevMode: boolean) => {
const newMode = !prevMode;
if (typeof localStorage !== "undefined") {
localStorage.setItem("darkMode", JSON.stringify(newMode));
}
return newMode;
});
};

return (
Expand Down

0 comments on commit f4befe8

Please sign in to comment.