2

Hey Guys I'm using Firebase Realtime Database to fetch some data for my React.js Web App.

There is a useState called Corr_User that should store the value of correct username.

I have a function to fetch the username from Firebase : -

 function Login(){

       const path =  firebase.database().ref("users").child(username);
       
        path.once("value")
        .then(snapShot => {            
            setCorr_User(snapShot.child("username").val());
             
        })

When I do this console.log(Corr_User) it prints a empty string indicating that the useState is not updated. For confirmation, I also logged the snapshot.val(). This printed the appropriate value.

I could understand from this that Firebase is too slow in returning response hence my useState is not getting updated. Is my understanding correct? Is there any way to make my Login() function wait for the response?

Please Help !! Thanks in Advance.

EDIT - Ok there was a bit of confusion I guess. The code goes likes this

 function Login(){
....
.once("value")
.then(snapShot => { // After fetching the data
 
 setCorr_User(snapShot.child("username").val()); // Assigning the value

 console.log(snapShot.val()); // This should be logged first

}) // End of function snapShot()

// This is still inside Login()
 console.log(Corr_User) // But this is logged first

} // End of Login()

It is from this, I was able to guess that Firebase is too slow in responding and useState is not getting updated accordingly as snapShot.val() is still empty.

  • I'm guess you tried to `console.log` it on the next line after setting it? You can't do that, state changes are asynchronous – Jayce444 Sep 26 '20 at 10:03
  • I did `console.log()` outside the function `snapShot` not inside that. Anyways How will I get to know whether the `useState` is updated or not. – Hard Code Programmer Sep 26 '20 at 10:06

1 Answers1

3

Data is loaded from Firebase asynchronously, and the then is called when that data is available. What this means in practice is that your console.log(Corr_User) is called before console.log(snapShot.val()). For this reason, any code that needs data from the database must be inside the then callback, or be called from there.

This is an incredibly common stumbling block for developers new to asynchronous APIs, so I recommend studying some of these links:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807