I want the background color of a Pressable preset to either blue or green based on the value present in firebase, i.e. if it is true in firebase, the color of the Pressable is green, else it is blue.
Also, if I press the button, it switches values in the firebase and also the color of the button swaps.
In my code, when I click the Pressable, the color changes and the value is swapped in firebase too, but it does not have the color preset when I load the application.
The button should have the color green the moment it loads if the value in firebase is true.
Here is my code.
import {StatusBar} from 'expo-status-bar';
import React, {Component} from 'react';
import {StyleSheet, Text, View, Pressable, TouchableOpacity} from 'react-native';
import {initializeApp} from 'firebase/app';
import {getDatabase, ref, onValue, set} from 'firebase/database';
import {color} from 'react-native-reanimated';
const firebaseConfig = {};
initializeApp(firebaseConfig);
export default class App extends Component {
constructor() {
super();
this.state = {
value: this.readVals('value/'),
};
}
readVals(path) {
const db = getDatabase();
const reference = ref(db, path);
onValue(reference, (snapshot) => {
const value = snapshot.val().obj;
return value;
});
}
setVals(path) {
const db = getDatabase();
const reference = ref(db, path);
const val = this.state.l1;
set(reference, {
obj: !val
});
this.state.l1 = !val;
}
render() {
return (
<View style={styles.container}>
<Pressable
style={({pressed}) => [
{
backgroundColor: this.state.value ? '#FF0000' : '#00FF00',
},
styles.button,
]} onPress={() => {this.setVals('value/')}}>
<Text style={styles.buttonText}>Button</Text>
</Pressable>
<StatusBar style="auto" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FF0000',
alignItems: 'center',
justifyContent: 'center',
},
button: {
flex: 0.15,
borderWidth: 1,
borderColor: 'rgba(0,0,0,0.25)',
alignItems: 'center',
justifyContent: 'center',
alignSelf: 'center',
borderWidth: 2,
borderRadius: 10,
marginTop: 20,
width: 200,
height: 100,
},
buttonText: {
fontWeight: 'bold',
fontSize: 20,
},
});
Is it possible to have the background color preset?
Please let me know how.
Thank you.
You need to change the state only after you fetched the value like this:
this.state = {
value: null;
};
readVals(path) {
const db = getDatabase();
const reference = ref(db, path);
onValue(reference, (snapshot) => {
const value = snapshot.val().obj;
this.setState({value: value});
});
}