Reputation: 425
Is it a normal behavior for Firebase to auto-refresh my app when data is modified in the database? Because I have not implemented any refreshing and all of a sudden I go back to my main window if I change a value from the database.
I read that setState
may cause the refreshing. So I intentionally added the following lines:
componentDidMount = () => {
this._ismounted = true;
}
componentWillUnmount = () => {
this._ismounted = false;
}
Every time I want to call setState I check if(this._ismounted)
, still somehow my app refreshes entirely.
I am quite inexperienced with Firebase and would definitely be happy to receive any kind of explanation or feedback regarding this matter.
This is how I am using firebase:
componentDidMount() {
this._ismounted = true;
const userId = firebase.auth().currentUser.uid;
firebase
.database().ref("users/" + userId).on("value", snapshot => {
if(this._ismounted) {
this.setState({
firstName: snapshot.child("firstName").val(),
lastName: snapshot.child("lastName").val(),
birthDay: snapshot.child("dateOfBirth").val()
}
});}
Upvotes: 0
Views: 3560
Reputation: 443
The best way to answer this without having a look at your code is to make you understand the basics of firebase.
Firebase has various types of listener a detailed description about it can be found in their official documentation over here. If you are using the 'on' listener with the 'value' event
database.child('/childNode').on('value', (snapshot) =>{this.setState(Object) })
The above piece of code will always change the data in your state which you are calling 'auto-refresh'. This will keep on changing data in your state until you don't detach the listener
On the other hand if you do
database.child('/childNode').once('value').then( (snapshot)=> { this.setState(Object)}).catch( err => console.log(err) )
This type of listener will only fetch you data once and even if your data in firebase changes it won't update the data in your state again.
Depending upon your requirements you should choose a suitable listener. Using a on value listener on a root node will fetch you everything in your database even if one small data is changed in some child node and whereas using once listener will fetch you stale data if you want to continuously keep the data updated.
Hope this helps. Feel free to ask for more explanation.
Edit:
In reference to the explanation above and your code ( assuming you only want to fetch data once and not update it again when it is changed in the database) you could use the once listener.
firebase.database().ref("users/" + userId).once("value").then( (snapshot) => {
this.setState({
firstName: snapshot.child("firstName").val(),
lastName: snapshot.child("lastName").val(),
birthDay: snapshot.child("dateOfBirth").val(),
});
}
Upvotes: 1