Ajax Success with React and Rails

advertisements

I've got a form that I am trying to handle with React. This is the ajax method in the handleSubmit function:

$.ajax({
  data: formData,
  dataType: "json",
  url: '/requests',
  type: "POST",
  success: function(data, status, xhr) {
    console.log('SHOW HERE ON RESPONSE');
    this.setState({
      formSubmitted: true
    });
  }
});

When I click on submit, I can see the POST request go through and the server responds with a 200. But the success callback is never entered, I don't see the console message.

My rails controller's action is just a simple:

return render nothing: true, status: 200 if request.xhr?

The log with the server response includes:

Completed 200 OK in 11ms (Views: 2.5ms | ActiveRecord: 2.6ms)

However when I move the stuff from the success callback in the ajax request to a complete callback then I see this error in the console:

Uncaught TypeError: this.setState is not a function


You are seeing this error, because this behaves differently inside $.ajax()'s success callback, because jQuery uses it internally.

Suppose you are executing the following ajax call in response to a click function, then:

var $this = $(this);
$.ajax({
  data: formData,
  dataType: "json",
  url: '/requests',
  type: "POST",
  success: function(data, status, xhr) {
    console.log('SHOW HERE ON RESPONSE');
      $this.setState({
      formSubmitted: true
    });
  }
});