Reputation: 25
I'm about to mark this.state in the Text tag. But the code I wrote does not show the value. What is the problem and how can I display it? And i want this.state value change
constructor(props){
super(props);
this.state= {
nickname: ""
}
}
componentWillMount(){
firebase.auth().onAuthStateChanged(user =>{
firebase.database()
.ref('/users/' + user.uid)
.once('value', function(snapshot){
console.log("snapshot value = "+snapshot.val().nickname)
var nickname = snapshot.val().nickname
console.log(nickname)
})
.then(
this.state.nickname = snapshot.val().nickname
)
})
}
Upvotes: 0
Views: 802
Reputation: 2922
first of all, you have to update the state
the proper way using this.setState({})
function, and then in order to show it in you <Text>
component you only need to pass the state that you need:
state= {
nickname: ""
}
componentWillMount() {
firebase.auth().onAuthStateChanged(user => {
firebase.database()
.ref('/users/' + user.uid)
.once('value', function(snapshot) {
console.log("snapshot value = "+snapshot.val().nickname)
let nickname = snapshot.val().nickname
console.log(nickname)
})
.then(
this.setState({ nickname: snapshot.val().nickname });
)
})
}
render() {
const { nickname } = this.state;
return (
<Text>{nickname}</Text>
);
}
Hopes this helps.
Upvotes: 1
Reputation: 16
Why don't you try this?
componentWillMount(){
firebase.auth().onAuthStateChanged(user =>{
firebase.database()
.ref('/users/' + user.uid)
.once('value', function(snapshot){
})
.then(rtnick => {
this.setState({ nickname:rtnick.val().nickname });
console.log(nickname);
})
})
}
Upvotes: 0
Reputation: 206
In your render function
<Text>{this.state.nickname}</ Text>
Edit:
componentWillMount(){
firebase.auth().onAuthStateChanged(user =>{
firebase.database()
.ref('/users/' + user.uid)
.once('value', function(snapshot){
console.log("snapshot value = "+snapshot.val().nickname)
var nickname = snapshot.val().nickname
console.log(nickname)
return nickname;
})
.then(nickname => {
this.setState({ nickname });
})
})
}
Upvotes: 0