James Lei James Lei - 5 months ago 25
jQuery Question

setState in $.get

Uncaught TypeError: undefined is not a function is throw when this.setState is use within the $.get scope, it works fine when I place the code outside the scope. How do you deal with it?

$.get(APIURL, function (data) {
this.setState({resdata: "This is a new state"});
});


I'm not sure what is the best practice to replace JQuery AJAX to other small AJAX libraries. Please advice.

Answer

You can save a reference to the outer this:

var that = this;
$.get(APIURL, function (data) {
   that.setState({resdata: "This is a new state"});
});

Or use $.proxy:

$.get(APIURL, $.proxy(function (data) {
   this.setState({resdata: "This is a new state"});
}, this));

The this you use inside the function normally refers to the jqXHR object, ref http://api.jquery.com/jquery.ajax/

Comments