On my react native app which i am developing this.setState is not working and not updating the value in the constructor . but this.state({}) is working. but when i am using that it is reseting the constructor Anyone please point what is wrong in this code
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, TextInput, Image } from 'react-native';
import { RkTextInput, RkButton } from 'react-native-ui-kitten';
import * as firebase from 'firebase';
export default class Home extends React.Component {
constructor(props) {
super(props)
this.state = {
uType: 'normal',
AdminNavbutton: ''
}
}
ProfileSubmithandler = () => {
alert(this.state.uType + " " + this.state.AdminNavbutton)
}
componentDidMount() {
this.readUserData();
}
readUserData = () => {
userstype = 'users/' + firebase.auth().currentUser.uid + '/userType'
firebase.database().ref(userstype).once('value').then(snapshot => {
this.setState({ uType: snapshot.val() }) // notworking and not updating uType
alert(snapshot.val()) //working Properly
})
}
emailid = () => {
}
render() {
return (
<View style={styles.container}>
<Text style={styles.titleText}>Taams</Text>
<Text style={styles.edition}>Developer's Edition</Text>
<Text style={styles.titleText}>Home</Text>
<Text>Alpha 0.0.0.1</Text>
<RkButton onPress={() => this.ProfileSubmithandler()}>
<Text style={styles.LoginButtonText}>Submit</Text>
</RkButton>
<TouchableOpacity onPress={() => this.props.navigation.navigate(this.state.AdminNavbutton)}><Text style={styles.signinButton}>Profile</Text></TouchableOpacity>
</View>
);
}
}
this.setState()
is asynchronous, your updated value will now be available right after calling it.
When setState()
is done updating your value, you will be able to access the updated data in your render
function under this.state.uType
.
If you wan to use your value right away in your function, you should put it in an other variable :
readUserData = () => {
userstype = 'users/' + firebase.auth().currentUser.uid + '/userType'
firebase.database().ref(userstype).once('value').then(snapshot => {
const uType = snapshot.val()
this.setState({ uType }) // notworking and not updating uType
alert(snapshot.val()) //working Properly
alert(uType) // Also working
})
}