Skip to content

Commit

Permalink
theme provider refactor (getSavedTheme + type)
Browse files Browse the repository at this point in the history
  • Loading branch information
nickzoum committed Aug 4, 2022
1 parent c837bfb commit a1c64b6
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions src/lib/themeProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ import {
} from 'react';

export type ThemeMode = 'light' | 'dark';
export type SavedThemeMode = ThemeMode | null;

const storageName = 'themeMode';
const attributeName = 'data-theme-mode';
// name of css property indicating mode
const themeProperty = '--default-theme';

interface ThemeContextType {
setThemeMode: (theme: ThemeMode | null) => void;
setThemeMode: (theme: SavedThemeMode) => void;
toggleThemeMode: () => void;
themeMode: ThemeMode;
}
Expand All @@ -25,15 +26,13 @@ const ThemeContext = createContext<ThemeContextType>({
themeMode: getTheme(),
});

const storedMode = localStorage.getItem(storageName) as ThemeMode | null;
const storedMode = getSavedTheme();
if (storedMode) {
document.documentElement.setAttribute(attributeName, storedMode);
}

export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [savedTheme, setSavedTheme] = useState(
localStorage.getItem(storageName) as ThemeMode | null
);
const [savedTheme, setSavedTheme] = useState(getSavedTheme());
const themeMode = savedTheme ?? getDefaultBrowserTheme();

const toggleThemeMode = useCallback(
Expand All @@ -48,7 +47,7 @@ export function ThemeProvider({ children }: { children: React.ReactNode }) {
return () => window.removeEventListener('storage', onStorageChange, false);

function onStorageChange() {
setSavedTheme(localStorage.getItem(storageName) as ThemeMode | null);
setSavedTheme(getSavedTheme());
}
}, []);

Expand Down Expand Up @@ -87,11 +86,12 @@ export function useThemeMode() {
return useContext(ThemeContext);
}

function getSavedTheme(): SavedThemeMode {
return localStorage.getItem(storageName) as SavedThemeMode;
}

export function getTheme(): ThemeMode {
return (
(localStorage.getItem(storageName) as ThemeMode | null) ??
getDefaultBrowserTheme()
);
return getSavedTheme() ?? getDefaultBrowserTheme();
}

export function getDefaultBrowserTheme(): ThemeMode {
Expand Down

0 comments on commit a1c64b6

Please sign in to comment.