1

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 })
     });
  }
rbxnt
  • 63
  • 1
  • 7
  • Possible duplicate of [React this.setState is not a function](https://stackoverflow.com/questions/31045716/react-this-setstate-is-not-a-function) – yanky_cranky Jun 15 '19 at 03:51

2 Answers2

3

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.

Jayce444
  • 8,725
  • 3
  • 27
  • 43
  • @Jayce444 now after you convert it to Arrow function, the keyword "this" in these function what's? – DevAS Jun 15 '19 at 10:03
0

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 })
     }); 
  }
yanky_cranky
  • 1,303
  • 1
  • 11
  • 16