Skip to content

Instantly share code, notes, and snippets.

@agustinfece
Last active June 18, 2021 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agustinfece/110af48536dae7cf43659d250b4fa2d2 to your computer and use it in GitHub Desktop.
Save agustinfece/110af48536dae7cf43659d250b4fa2d2 to your computer and use it in GitHub Desktop.
App.js
import { StatusBar } from 'expo-status-bar';
import React, { useEffect, useState } from 'react';
import { StyleSheet, View, Switch } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
export default function App() {
const [isEnabled, setIsEnabled] = useState(false);
const getTheme = async () => {
try {
const theme = await AsyncStorage.getItem('theme');
return theme;
} catch(error) {
console.log('error', error);
};
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: `${isEnabled ? '#fff' : '#000'}`,
alignItems: 'center',
justifyContent: 'center',
},
});
const setTheme = async (theme) => {
try {
await AsyncStorage.setItem('theme', theme);
} catch(error) {
console.log('error', error);
};
};
useEffect(() => {
getTheme()
.then(res => {
setIsEnabled(res === 'light');
})
.catch(err => {
console.log('error', err);
});
}, []);
const onChangeHandler = (value) => {
if (value) {
setIsEnabled(true);
setTheme('light');
} else {
setIsEnabled(false);
setTheme('dark');
};
};
return (
<View style={styles.container}>
<Switch
onValueChange={onChangeHandler}
value={isEnabled}
/>
<StatusBar style="auto" />
</View>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment