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.