| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- import React, { useState, useEffect, createContext, useContext } from "react";
- import { useColorScheme } from "react-native";
- import { THEME } from "@Constants/localStorage";
- import { getObjectData } from "@Service/asyncStorage";
- import { lightColors, darkColors } from "./colors";
-
- export const ThemeContext = createContext({
- isDark: false,
- colors: lightColors,
- setScheme: () => {},
- });
-
- export const ThemeProvider = (props) => {
- // Getting the device color theme, this will also work with react-native-web
- const deviceColorScheme = useColorScheme(); // Can be dark | light | no-preference
-
- /*
- * To enable changing the app theme dynamically in the app (run-time)
- * we're gonna use useState so we can override the default device theme
- */
- const [isDark, setIsDark] = useState(null);
-
- const handleTheme = async () => {
- const theme = await getObjectData(THEME);
- if (theme !== null) {
- setIsDark(theme.type === "dark");
- } else {
- setIsDark(deviceColorScheme === "dark");
- }
- };
-
- // Get the theme from async storage on mount
- useEffect(() => {
- handleTheme();
- }, []);
-
- const defaultTheme = {
- isDark,
- // Changing color schemes according to theme
- colors: isDark ? darkColors : lightColors,
- // Overrides the isDark value will cause re-render inside the context.
- setScheme: async (scheme) => {
- setIsDark(scheme === "dark");
- },
- };
-
- return (
- <ThemeContext.Provider value={defaultTheme}>
- {props.children}
- </ThemeContext.Provider>
- );
- };
-
- // Custom hook to get the theme object returns {isDark, colors, setScheme}
- export const useTheme = () => useContext(ThemeContext);
|