Reputation:
Why my state is not updating with the data that im fetching directly from direbase
Where im getting data in console
What im doing wrong here,
Error is here
Upvotes: 0
Views: 50
Reputation: 80944
Change this:
const db = firebase.database().ref('users/trainers/'+uid).on('value', function(snapshot){
// here this refers to the firebase callback scope
this.setState({
.........
.........
})
}))
into this:
const db = firebase.database().ref('users/trainers/'+uid).on('value', (snapshot) =>{
// here this refers to the firebase callback scope
this.setState({
.........
.........
})
}))
Use arrow functions:
An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.
Upvotes: 1
Reputation: 6130
Here the problem is your this
is not in the scope, this
in here refers to firebase callback scope. You can console this
and check.
const db = firebase.database().ref('users/trainers/'+uid).on('value', function(snapshot){
// here this refers to the firebase callback scope
this.setState({
.........
.........
})
}))
Fix you can do is
const that = this;
const db = firebase.database().ref('users/trainers/'+uid).on('value', function(snapshot){
// now `that` holds your class LogPro1 scope, now you can setState using that.setState()
that.setState({
.........
.........
})
}))
Upvotes: 1
Reputation: 2252
Change your getData() method definition like below,
getData = () => {
... As the above code
}
OR
bind this to the getData method in the constructor.
constructor() {
super(props);
this.state = { email: '', firstName: '', lastName: '' }
this.getData = this.getData.bind(this); // Binding this context to getData method
}
Upvotes: 0