import { useColorScheme } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useState, useEffect } from 'react';
const MyComponent = () => {
const colorScheme = useColorScheme(); // "light" or "dark"
const [themePreference, setThemePreference] = useState(null); // "system", "light", "dark"
const [isSystemMode, setIsSystemMode] = useState(false);
useEffect(() => {
const loadThemePreference = async () => {
try {
const storedPreference = await AsyncStorage.getItem('themePreference');
if (storedPreference) {
setThemePreference(storedPreference);
} else {
// Default to system if no preference is stored
setThemePreference('system');
}
} catch (e) {
console.error("Error loading theme preference:", e);
setThemePreference('system'); // Default on error
}
};
loadThemePreference();
}, []);
useEffect(() => {
if (themePreference === 'system') {
setIsSystemMode(true); // If the preference is system, we're in system mode
} else {
setIsSystemMode(false); // Otherwise, we're forcing light or dark
}
}, [themePreference]);
// Function to set theme preference (example)
const setTheme = async (newTheme) => {
try {
await AsyncStorage.setItem('themePreference', newTheme);
setThemePreference(newTheme);
} catch (e) {
console.error("Error saving theme preference:", e);
}
};
return (
{isSystemMode ? "System Mode Enabled" : "System Mode Disabled"}
{/* Use this function to set theme preference, triggerring re-render*/}
<button =="" onpress="{()"> setTheme('light')}>Force Light Mode</button>
This approach allows you to accurately determine if your app is in "system mode" based on your stored preference, and it integrates well with NativeWind's ability to style your components based on the actual color scheme. Remember to adapt the AsyncStorage keys and theme preference values to match your application's specific needs.