@@ -5,28 +5,26 @@ import React, { createContext, useState, useEffect } from 'react';
55export const ThemeContext = createContext ( ) ;
66
77export const ThemeProvider = ( { children } ) => {
8- const [ theme , setTheme ] = useState ( 'dark' ) ;
9-
10- const toggleTheme = ( ) => {
11- setTheme ( theme === 'light' ? 'dark' : 'light' ) ;
12- } ;
8+ const [ theme , setTheme ] = useState ( ) ;
139
1410 useEffect ( ( ) => {
1511 const localTheme = localStorage . getItem ( 'theme' ) ;
16- console . log ( 'localTheme ' , localTheme ) ;
12+ console . log ( 'Get LocalStorage theme ' , localTheme ) ;
1713
18- if ( localTheme ) {
19- setTheme ( localTheme ) ;
20- } else {
21- const prefersDarkMode = window . matchMedia ( '(prefers-color-scheme: dark)' ) . matches ;
22- setTheme ( prefersDarkMode ? 'dark' : 'light' ) ;
23- }
14+ setTheme ( localTheme || 'dark' ) ;
2415 } , [ ] ) ;
2516
17+ const toggleTheme = ( ) => {
18+ setTheme ( theme === 'light' ? 'dark' : 'light' ) ;
19+ } ;
20+
2621 useEffect ( ( ) => {
27- localStorage . setItem ( 'theme' , theme ) ;
28- document . documentElement . setAttribute ( 'data-theme' , theme ) ; // set data-theme attribute on the root HTML tag
29- console . log ( 'theme' , theme ) ;
22+ // if theme available and not equal to undefined or null
23+ if ( theme && theme !== 'undefined' && theme !== 'null' ) {
24+ localStorage . setItem ( 'theme' , theme ) ;
25+ console . log ( 'Set LocalStorage theme' , theme ) ;
26+ document . documentElement . setAttribute ( 'data-theme' , theme ) ;
27+ }
3028 } , [ theme ] ) ;
3129
3230 return (
0 commit comments