Reputation: 11
I am a newbie in react JS and I am trying to pull data from a url in Json format. I did the following but I keep on getting a feeback at the console as
Rovers: undefined.
How do I go about it when am supposed to get something like
Rovers:[object, object, object]
class App extends React.Component {
constructor(props){
super(props);
this.state={rovers:[]};
}
componentWillMount(){
api.getRovers().then((response) =>{
this.setState({
rovers: response.rovers
});
});
}
render() {
console.log("Rovers: ", this.state.rovers);
}
and this is where am calling the json link
var api={
getRovers(){
var url='https://jsonplaceholder.typicode.com/posts/1';
return fetch(url).then((response)=> response.json());
}
};
module.exports=api;
Upvotes: 0
Views: 3146
Reputation: 93193
The endpoint replies with object that does not include rovers
. However, it includes : id
, userId
, title
and body
That's why response.rovers
is undefined
. Then this.state.rovers
is the same
body
instead of rovers
, in this case , replace:componentWillMount(){
api.getRovers().then((response) =>{
this.setState({
rovers: response.rovers
});
});
}
By :
componentWillMount(){
api.getRovers().then((response) =>{
this.setState({
rovers: response.body.split('\n')
});
});
}
Upvotes: 2