0

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.

quentin mayer
  • 137
  • 1
  • 1
  • 12

2 Answers2

1

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.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

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)
});
Jaydeep Galani
  • 4,842
  • 3
  • 27
  • 47
  • Hello, i already tried this its not working i get :react native possible unhandled promise rejection (id 0) Typeerror: this.setState is not a function – quentin mayer Mar 14 '19 at 18:32
  • did you bind `this` to the method in which this code resides ? – Jaydeep Galani Mar 15 '19 at 04:22
  • i resolvd my problem here :https://stackoverflow.com/questions/55170390/reactassign-firebase-snapshot-to-a-variable-outside-of-the-function/55170672?noredirect=1#comment97083268_55170672 – quentin mayer Mar 15 '19 at 13:20