Throwing "unexpected token" error, when i use jsop api in reactjs?

- 1 answer

Ad

When i used to fetch data from json api its throwing "Unexpected token" error. Below, i've added my code what i have tried so far. Get me out from this issue. I'm trying to solve this problem long time.

Here,

var Demo = React.createClass({
    render: function() {
        getInitialState:function(){
            return {
                data:[]
            };
        },
        componentDidMount: function () {
            $.ajax({
              url: "http://www.w3schools.com/angular/customers.php"
            }).done(function(data) {
              this.setState({data: data})
            });
        },
        return (
            <div>
                {this.props.data.map(function(el,i) {
                    return <div key={i}>
                        <div>{el.Name}</div>
                        <div>{el.City}</div>
                        <div>{el.Country}</div>
                    </div>;
                }
            </div>
        );
    }
});

var Stream = React.createClass({
  render: function() {
    return (
        <div>
            <div className="scrollContent ">
                <Demo />
            </div>
        </div>
    );
  }
});
Ad

Answer

Ad

You have several errors in your code

  1. move getInitialState and componentDidMount from render method, these methods should be as children of your component (Demo) class but not as children of render method
  2. add dataType: 'json' to $.ajax, because now it returns string, but in your case you need get json
  3. as you are using this.setState in .done you should set this to .done callback, because now this refers to $.ajax object not Demo, you can use .bind method to do it.
  4. change this.props.data to this.state.data because data located in state object not in props
  5. array with data located in records property use it instead of just data

Example

var Demo = React.createClass({
  getInitialState:function() {
    return {
      data :[]
    };
  },

  componentDidMount: function () {
    $.ajax({
      url: "http://www.w3schools.com/angular/customers.php",
      dataType: 'json'
    }).done(function(response) {
      this.setState({ data: response.records });
    }.bind(this));
  },

  render: function() {
    var customers = this.state.data.map(function(el,i) {
      return <div key={i}>
        <div>{el.Name}</div>
        <div>{el.City}</div>
        <div>{el.Country}</div>
      </div>
    });

    return <div>{ customers }</div>;
  }
});
Ad
source: stackoverflow.com
Ad