Skip to content

Commit

Permalink
Added event listener and older browser support
Browse files Browse the repository at this point in the history
  • Loading branch information
aarya-16 committed Oct 25, 2024
1 parent 77e9457 commit 8c2151d
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions Client/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,14 @@ import { networkService } from "./main";
import { setMode } from "./Features/UI/uiSlice";

const getPreferredTheme = () => {
if(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark';
try {
return window?.matchMedia?.('(prefers-color-scheme: dark)')?.matches? 'dark': 'light';
}
catch {
return 'light';
}
return 'light';
}

function App() {
const AdminCheckedRegister = withAdminCheck(Register);
const MonitorsWithAdminProp = withAdminProp(Monitors);
Expand All @@ -69,6 +72,17 @@ function App() {
useEffect(() => {
const theme = getPreferredTheme();
dispatch(setMode(theme));

const mediaQuery = window?.matchMedia?.('(prefers-color-scheme: dark)');
const handleThemeChange = (e) => {
dispatch(setMode(e.matches ? 'dark' : 'light'));
};

mediaQuery?.addEventListener?.('change', handleThemeChange);

return () => {
mediaQuery?.removeEventListener?.('change', handleThemeChange);
};
},[dispatch]);

// Cleanup
Expand Down

0 comments on commit 8c2151d

Please sign in to comment.