Ad

"this" Is Null In Firebase Query Function In Reactjs

- 1 answer

In componentDidMount, the first console.log(this) gives me the right response("ThumbNail {props: Object, context: Object, refs: Object, updater: Object, state: Object…}")

but when used in the firebase query (i.e. orderbyChild) its console.log(this) returns null. I am trying to use the function "this.handleArticle" in the query but I keep getting this error "Cannot read property '_handleArticle' of null".

componentDidMount() {
            //adds the change listener to listen to changes in TeamStore
            TeamStore.addChangeListener(this._onChange);
            // triggers updateArticle
            // bind article to current state.name
            this._updateArticle();
            console.log(this); //this one is right

        //get new article as notification
        var teamResRef = new Firebase(this.props.baseUrl + this.state.name + '/results');
        teamResRef.orderByChild('timeStamp').startAt(Date.now()).on('child_added', function(snapshot) {
            var newArticle = snapshot.val();

            // console.log(newArticle);
            // _handleArticle(newArticle);
             console.log(this); //this one returns null
        });
    }
Ad

Answer

You need set this to callback function (because in callback this does not refer to React component Object), to do it you can use .bind method like this

teamResRef
  .orderByChild('timeStamp')
  .startAt(Date.now())
  .on('child_added', function(snapshot) {
     // code
  }.bind(this));

as mentioned @David East, you can also set this through fourth parameter in .on, like this

teamResRef
  .orderByChild('timeStamp')
  .startAt(Date.now())
  .on('child_added', function(snapshot) {
      // code
   }, null, this);
Ad
source: stackoverflow.com
Ad