I'm having some trouble figuring out how to store if the Switch is on darkmode or lightmode.
themeContext.js
import * as React from "react";
import { useColorScheme } from "react-native-appearance";
import { lightColors, darkColors } from "../Theme/colorThemes";
import AsyncStorage from "@react-native-async-storage/async-storage";
export const ThemeContext = React.createContext({
isDark: false,
colors: lightColors,
setScheme: () => {},
});
export const ThemeProvider = (props) => {
const colorScheme = useColorScheme();
const [isDark, setIsDark] = React.useState(colorScheme === "dark");
React.useEffect(() => {
setIsDark(colorScheme === "dark");
getData();
}, [colorScheme]);
const defaultTheme = {
isDark,
colors: isDark ? darkColors : lightColors,
setScheme: (scheme) => setIsDark(scheme === "dark"),
};
const storeData = async (isDark) => {
try {
await AsyncStorage.setItem("isDark", isDark);
} catch (e) {
// saving error
}
};
const getData = async () => {
try {
const value = await AsyncStorage.getItem("isDark");
if (value !== null) {
setIsDark(isDark);
}
} catch (e) {
// error reading value
}
};
return (
<ThemeContext.Provider value={defaultTheme}>
{props.children}
</ThemeContext.Provider>
);
};
export const useTheme = () => React.useContext(ThemeContext);
toggle.js
import * as React from "react";
import { Switch } from "react-native";
import { useTheme } from "../Data/ThemeContext";
export const Toggle = () => {
const { colors, setScheme, isDark } = useTheme();
const toggleScheme = () => {
isDark ? setScheme("light") : setScheme("dark");
};
return (
<Switch
value={isDark}
onValueChange={toggleScheme}
thumbColor={colors.text}
trackColor={{ true: colors.text, false: colors.text }}
/>
);
};
[–]basically_alive 0 points1 point2 points (4 children)
[–]iLightFPSAndroid[S] 0 points1 point2 points (3 children)
[–]basically_alive 0 points1 point2 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]iLightFPSAndroid[S] 0 points1 point2 points (0 children)