'this.setState is not working when using firebase database
I am using the state to get value from the firebase database but I think there is some problem while doing it.
const dbRef=firebase.database().ref().child('profiles').child(user.uid).child('displayName')
dbRef.on('value',snapshot=>{
this.setState({ profile:{ position:snapshot.val() } })
})
console.log(this.state)
Solution 1:[1]
Both loading data from Firebase and setting the state of React are asynchronous operations. This means that your main code continues to run, while the data is being loaded, or the state is being modified.
You can learn a lot about such asynchronous code, by adding some simple logging statements in your current code:
const dbRef=firebase.database().ref().child('profiles').child(user.uid).child('displayName')
console.log("Before starting listener");
dbRef.on('value',snapshot=>{
console.log("Got data, start to set state");
this.setState({ profile:{ position:snapshot.val() } }, function() {
console.log("The state has been set");
})
console.log("Started to set state");
})
console.log("After starting listener");
The new function I added to setState
is a callback that is called after the state has been modified, similar to how Firebase has a callback that is called after the data comes back fro. the database.
When you run the above code, the output is:
Before starting listener
After starting listener
Got data, start to set state
Started to set state
The state has been set
This is probably not the order you expected, but it is completely normal for asynchronous operations. The callback functions you pass in get called out of the normal operating sequence, once the asynchronous operation completes.
This means that any code that needs to run after the state has been set, which in turn depends on the database data, needs to be inside the inner callback that I added in my code above.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |