React Setting State From Data Recieved In Ajax call

Question!

I'm trying to get some data from my server with an AJAX call that looks like

fetch_reviews() {
    var scraper_url = this.props.thing.text
    var all_the_data = $.get({
      url: window.location.origin+'/fetch_review_data', 
      data: {scraper_url: scraper_url}
    }).success(function(data){
      this.state.allReviews = data
    });
  } 

onle I keep getting the error "cannot read property allReviews of undefined"

How can I set the state of allReviews from inside the success function?



Answers
You should use arrow function(if you use ES2015) or .bind in order to set this that will refer to your Component object, because now this refers to global scope(window or undefined if you use strict mode),

// ...
.success((data) => {
   this.setState({ allReviews: data })
});

or

// ...
.success(function (data) {
   this.setState({ allReviews: data })
}.bind(this));

also if you need set new state in React you must use setState method



Your this changes to $.get execution scope while your state is attached to react's execution scope which is not accessible inside your fetch. So hold your this in a variable...

fetch_reviews() {
        var scraper_url = this.props.thing.text;
        var that = this; // hold this in another variable
        var all_the_data = $.get({
          url: window.location.origin+'/fetch_review_data', 
          data: {scraper_url: scraper_url}
        }).success(function(data){
          that.setState({allReviews : data });
        });
      } 
By : Moid Mohd


This video can help you solving your question :)
By: admin