clean up into hook
parent
9a86f0dae4
commit
01870883d6
|
@ -3,7 +3,7 @@ import React, {ReactNode, createContext, useContext} from 'react'
|
||||||
import {
|
import {
|
||||||
AppState,
|
AppState,
|
||||||
TextStyle,
|
TextStyle,
|
||||||
useColorScheme,
|
useColorScheme as useColorScheme_BUGGY,
|
||||||
ViewStyle,
|
ViewStyle,
|
||||||
ColorSchemeName,
|
ColorSchemeName,
|
||||||
} from 'react-native'
|
} from 'react-native'
|
||||||
|
@ -93,31 +93,36 @@ export const ThemeContext = createContext<Theme>(defaultTheme)
|
||||||
|
|
||||||
export const useTheme = () => useContext(ThemeContext)
|
export const useTheme = () => useContext(ThemeContext)
|
||||||
|
|
||||||
const getTheme = (theme: ColorSchemeName) =>
|
function getTheme(theme: ColorSchemeName) {
|
||||||
theme === 'dark' ? darkTheme : defaultTheme
|
return theme === 'dark' ? darkTheme : defaultTheme
|
||||||
|
}
|
||||||
|
|
||||||
|
function useColorScheme_FIXED() {
|
||||||
|
const colorScheme = useColorScheme_BUGGY()
|
||||||
|
const [currentColorScheme, setCurrentColorScheme] =
|
||||||
|
React.useState<ColorSchemeName>(colorScheme)
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
// we don't need to be updating state on web
|
||||||
|
if (isWeb) return
|
||||||
|
const subscription = AppState.addEventListener('change', state => {
|
||||||
|
const isActive = state === 'active'
|
||||||
|
if (!isActive) return
|
||||||
|
setCurrentColorScheme(colorScheme)
|
||||||
|
})
|
||||||
|
return () => subscription.remove()
|
||||||
|
}, [colorScheme])
|
||||||
|
|
||||||
|
return isWeb ? colorScheme : currentColorScheme
|
||||||
|
}
|
||||||
|
|
||||||
export const ThemeProvider: React.FC<ThemeProviderProps> = ({
|
export const ThemeProvider: React.FC<ThemeProviderProps> = ({
|
||||||
theme,
|
theme,
|
||||||
children,
|
children,
|
||||||
}) => {
|
}) => {
|
||||||
const colorSchemeFromRN = useColorScheme()
|
const colorScheme = useColorScheme_FIXED()
|
||||||
const [statefulColorScheme, setStatefulColorScheme] =
|
|
||||||
React.useState<ColorSchemeName>(colorSchemeFromRN)
|
|
||||||
const colorScheme = isWeb ? colorSchemeFromRN : statefulColorScheme
|
|
||||||
const themeValue = getTheme(theme === 'system' ? colorScheme : theme)
|
const themeValue = getTheme(theme === 'system' ? colorScheme : theme)
|
||||||
|
|
||||||
React.useEffect(() => {
|
|
||||||
if (!isWeb) return
|
|
||||||
const subscription = AppState.addEventListener('change', state => {
|
|
||||||
const isActive = state === 'active'
|
|
||||||
|
|
||||||
if (!isActive) return
|
|
||||||
|
|
||||||
setStatefulColorScheme(colorSchemeFromRN)
|
|
||||||
})
|
|
||||||
return () => subscription.remove()
|
|
||||||
}, [colorSchemeFromRN])
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ThemeContext.Provider value={themeValue}>{children}</ThemeContext.Provider>
|
<ThemeContext.Provider value={themeValue}>{children}</ThemeContext.Provider>
|
||||||
)
|
)
|
||||||
|
|
Loading…
Reference in New Issue