user12672898
user12672898

Reputation:

TypeError: Cannot read property 'setState' of null, fetching data directly from firebase rtdb

Why my state is not updating with the data that im fetching directly from direbase enter image description here

Where im getting data in console

enter image description here

What im doing wrong here, Error is here enter image description here

Upvotes: 0

Views: 50

Answers (3)

Peter Haddad
Peter Haddad

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

Akhil Aravind
Akhil Aravind

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

Gangadhar Gandi
Gangadhar Gandi

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

Related Questions