Reputation: 137
i trying to get the data from my database, in componentWillMount(), it works fine with this :
var userData = null
firebase.database().ref('/users/' + user.uid).once('value').then(function(snapshot) {
userData = snapshot.val()
console.log(userData)
});
But it only works in the method only, i tried to asign the value to a variable but i can't get it outside even with this.setstate. I am really lost it looks easy but i don't know how ... Thanks for help.
Upvotes: 0
Views: 1386
Reputation: 4961
Well, what's happening here is,
your firebase method is taking a time to get data and because everything is asynchronous here, javascript will not wait until your firebase method is executed.
Immediate next line of firebase.database()....
will be executed before this completes.
So you might need to set your data into state using setState
or you can use a class variable instead of a local variable.
do this,
constructor(props){
super(props);
this.state={
data:null //either do this
}
this.localData=null; // or this
}
firebase.database().ref('/users/' + user.uid).once('value').then(function(snapshot) {
this.setState({data:snapshot.val()});
this.localData = snapshot.val();
console.log(this.localData)
});
Upvotes: 0
Reputation: 317372
once()
is asynchronous and returns immediately with a promise. The promise does not block your code when you attach a then
callback to it. userData
won't be populated in the callback from the promise until after the database query completes, and you have no guarantee when that will be. If your code tries to access userData before it's finally populated, it will still have its original null value.
Upvotes: 1