rbxnt
rbxnt

Reputation: 63

How to setState in componentDidMount?

Working on this project and trying to call firebase real-time database information then setting a state after calling it so I can use it in the render. This is my code currently but its saying setState is unknown, I've tried to read up on other solutions to this problem but don't understand it, any help would be appreciated. Thanks.

  componentDidMount(){
    this._getLocationAsync();
    firebase.database().ref('pets/').once('value', function (snapshot) {
        this.setState({ testdid: snapshot.val().name })
     });
  }

Upvotes: 1

Views: 511

Answers (2)

yanky_cranky
yanky_cranky

Reputation: 1363

Your callback is made in different context, you need to do :

 componentDidMount(){
    this._getLocationAsync();
    firebase.database().ref('pets/').once('value', function (snapshot) {
        this.setState({ testdid: snapshot.val().name })
     }.bind(this));  // bind to current context
  }

or with ES6, which i prefer


componentDidMount(){
    this._getLocationAsync();
    firebase.database().ref('pets/').once('value', snapshot => { // Using Fat Arrow
        this.setState({ testdid: snapshot.val().name })
     }); 
  }

Upvotes: 0

Jayce444
Jayce444

Reputation: 9063

The short answer is because this in your firebase callback refers to that function itself, rather than the component. Using an arrow function should correctly bind this to the component should fix your error:

firebase.database().ref('pets/').once('value', (snapshot) => {
    this.setState({ testdid: snapshot.val().name })
 });

Read up on scope in JS, particularly in regards to the this keyword. Definitely important to know, cos it has some weird behaviour sometimes.

Upvotes: 3

Related Questions