Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import React, { useState, useEffect, createContext, useContext } from "react";
  2. import { useColorScheme } from "react-native";
  3. import { THEME } from "@constants/localStorage";
  4. import { getObjectData } from "@service/asyncStorage";
  5. import { lightColors, darkColors } from "./colors";
  6. export const ThemeContext = createContext({
  7. isDark: false,
  8. colors: lightColors,
  9. setScheme: () => {},
  10. });
  11. export const ThemeProvider = (props) => {
  12. // Getting the device color theme, this will also work with react-native-web
  13. const deviceColorScheme = useColorScheme(); // Can be dark | light | no-preference
  14. /*
  15. * To enable changing the app theme dynamically in the app (run-time)
  16. * we're gonna use useState so we can override the default device theme
  17. */
  18. const [isDark, setIsDark] = useState(null);
  19. const handleTheme = async () => {
  20. const theme = await getObjectData(THEME);
  21. if (theme !== null) {
  22. setIsDark(theme.type === "dark");
  23. } else {
  24. setIsDark(deviceColorScheme === "dark");
  25. }
  26. };
  27. // Get the theme from async storage on mount
  28. useEffect(() => {
  29. handleTheme();
  30. }, []);
  31. const defaultTheme = {
  32. isDark,
  33. // Changing color schemes according to theme
  34. colors: isDark ? darkColors : lightColors,
  35. // Overrides the isDark value will cause re-render inside the context.
  36. setScheme: async (scheme) => {
  37. setIsDark(scheme === "dark");
  38. },
  39. };
  40. return (
  41. <ThemeContext.Provider value={defaultTheme}>
  42. {props.children}
  43. </ThemeContext.Provider>
  44. );
  45. };
  46. // Custom hook to get the theme object returns {isDark, colors, setScheme}
  47. export const useTheme = () => useContext(ThemeContext);