SetState in $ .get

Uncaught TypeError: undefined is not a throw function when this.setState is used in the $ .get scope, it works fine when I put code out of scope. How do you deal with this?

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

I am not sure if it is best to replace JQuery AJAX with other small AJAX libraries. Please advice.

+4
source share
2 answers

You can save the link to external 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));

thiswhich you use inside the function usually refers to the jqXHR object, ref http://api.jquery.com/jquery.ajax/

+11
source

bind (this), React Documentation:

https://facebook.imtqy.com/react/tips/initial-ajax.html

:

componentDidMount: function() {
    this.serverRequest = $.get(this.props.source, function (result) {
      var lastGist = result[0];
      this.setState({
        username: lastGist.owner.login,
        lastGistUrl: lastGist.html_url
      });
    }.bind(this));
  },
+2

All Articles