All files / Themes ThemeProvider.tsx

76% Statements 19/25
62.5% Branches 5/8
62.5% Functions 5/8
76% Lines 19/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63                36x         36x   36x             1x   1x 1x         1x   1x 1x 1x       1x         1x         1x 1x     1x     36x 1255x 1255x     1255x    
import { createContext, useContext, useState, useEffect } from 'react';
import { ThemeColors } from './Themes.d';
 
interface ThemeState {
  theme: ThemeColors;
  setTheme: (theme: ThemeColors) => void;
}
 
const initialThemeState: ThemeState = {
  theme: 'light' as ThemeColors,
  setTheme: () => null,
};
 
const ThemeContext = createContext<ThemeState>(initialThemeState);
 
export const ThemeProvider = ({
  theme,
  children,
}: {
  theme?: ThemeColors;
  children: React.ReactNode;
}) => {
  const [selectedTheme, setSelectedTheme] = useState<ThemeColors>(theme || initialThemeState.theme);
 
  useEffect(() => {
    Iif (theme) {
      setSelectedTheme(theme);
    }
  }, [theme]);
 
  useEffect(() => {
    // const stored = localStorage.getItem('selectedTheme');
    const stored = 'light'
    Eif (stored) {
      setSelectedTheme(stored as ThemeColors);
    }
  }, []);
 
  const handleThemeChange = (theme: ThemeColors) => {
    setSelectedTheme(theme);
    localStorage.setItem('selectedTheme', theme);
  };
 
  const value = {
    theme: selectedTheme,
    setTheme: (theme: ThemeColors) => handleThemeChange(theme),
  };
 
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', selectedTheme);
  }, [selectedTheme]);
 
  return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
};
 
export const useTheme = () => {
  const context = useContext(ThemeContext);
  Iif (!context) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};