Throwing "unexpected token" error, when i use jsop api in reactjs?
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
- move
getInitialState
andcomponentDidMount
fromrender
method, these methods should be as children of your component (Demo
) class but not as children ofrender
method - add
dataType: 'json'
to$.ajax
, because now it returns string, but in your case you need getjson
- as you are using
this.setState
in.done
you should setthis
to.done
callback, because nowthis
refers to$.ajax
object notDemo
, you can use.bind
method to do it. - change
this.props.data
tothis.state.data
because data located in state object not in props - array with data located in
records
property use it instead of justdata
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
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad