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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With