1

I'm trying to solve the following:
I have two methods within my Component:
getData requests the data and gets approximate time when the results will be ready.
I want to set setTimeout for that delay and than pass the request id to method processData, which makes another request to retrieve the actual data using the request id it got from requestData I am trying to access.
I am unable to reference the processData from within setTimeout in ajax's success. How to do that? I've tried this.processData, this.refs., processData without success.

var Component = React.createClass({
processData: function(id) {
 // ajax gets the data using the id (which we got from sending the request in requestData)
},
requestData: function(colid) {
$.ajax({
            url: "/api/getvalues/id/"+colid,
            type: "GET",
            cache: false,
            dataType: 'json',
            success: function(data) {
                setTimeout(function() {this.refs.processData(data.id);}, data.estimatedWaitTime+250);
            }
});
}
});
Kokesh
  • 3,165
  • 7
  • 29
  • 46

2 Answers2

4

If you want to use the component's context (e.g. this), then you must bind the context in any callback. Otherwise, this will change its meaning:

requestData: function(colid) {
$.ajax({
            url: "/api/getvalues/id/"+colid,
            type: "GET",
            cache: false,
            dataType: 'json',
            success: function(data) {
                setTimeout(function() {this.refs.processData(data.id);}.bind(this), data.estimatedWaitTime+250);
            }.bind(this)
    });
}

For your example, in order to tunnel the context down to the setTimeout callback, you need to bind both the ajax callback and the setTimeout callback.

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
  • wouldn't `setTimeout(this.refs.processData(data.id), data.estimatedWaitTime+250)` and bind only the `ajax` also work? – Joel Almeida Jul 07 '15 at 08:27
  • 1
    @JoelAlmeida Not exactly, because `this.refs.processData(data.id)` won't *return* a function. And `setTimeout` takes a function as a parameter. – Davin Tryon Jul 07 '15 at 08:28
1

Assign the this to another local variable (say _this) before the setTimemout

success: function(data) {
   var _this = this;
   setTimeout(function() {//.....use _this here ......}, data.estimatedWaitTime+250);
}

Becuase inside the setTimeout this means window

Refer Pass correct "this" context to setTimeout callback?

Community
  • 1
  • 1
Dickens A S
  • 3,824
  • 2
  • 22
  • 45