Currently, I am implementing contextAPI along with useState, where the initial value is an Object containing Themes.
However, when I try to log this in the console, it returns undefined.
export interface ITheme {
themeMode: DefaultTheme
setThemeMode: Dispatch<SetStateAction<DefaultTheme>>
}
interface IThemeProviderProps {
children: ReactNode
}
const initialValues: ITheme = {
themeMode: themesSchema.light,
setThemeMode: () => null
}
export const ToggleThemeContext = createContext<ITheme>({} as ITheme)
export function ToggleThemeContextProvider({ children }: IThemeProviderProps) {
const deviceTheme = useColorScheme()
const firstThemeChoice = themesSchema[deviceTheme ? deviceTheme : 'light']
const [themeMode, setThemeMode] = useState<DefaultTheme>(firstThemeChoice)
const value = {
themeMode,
setThemeMode
}
return (
<ToggleThemeContext.Provider value={value}>
{children}
</ToggleThemeContext.Provider>
)
}
I have also created a custom hook for accessing this functionality:
export function useToggleTheme(): ITheme {
const context = useContext(ToggleThemeContext)
//In using this hook, remember to pass in the setThemeMode(example)
//where example -----> const example = colorScheme['light' | 'dark']
return context
}
In my App, I utilized a provider. However, encountering issues because I need to utilize ThemeProvider from styled-components:
const { themeMode } = useToggleTheme()
console.log(themeMode) //Undefined
This is a snippet of my App:
export default function App() {
const { themeMode } = useToggleTheme()
return (
<HeaderContextProvider>
<ToggleThemeContextProvider>
<ThemeProvider theme={themeMode}>
<SafeAreaProvider>
{fontsLoaded ? <Routes /> : <Loading />}
<StatusBar style="auto" backgroundColor="transparent" translucent />
</SafeAreaProvider>
</ThemeProvider>
</ToggleThemeContextProvider>
</HeaderContextProvider>
)
}
Initially, I tried setting InitialValues in createContext. However, upon using setThemeMode, it does not work. This issue persists in other contexts that simply return undefined with boolean values as well when setXXX is used to update the state.