Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setState in $.get

When this.setState() is used within the $.get scope I get the following error

Uncaught TypeError: undefined is not a function

It works fine outside the $.get scope.

How can I fix this?

$.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.

like image 728
James Lei Avatar asked Nov 27 '14 16:11

James Lei


1 Answers

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/

like image 147
blgt Avatar answered Sep 21 '22 02:09

blgt