0

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;
2
  • How are you calling render()? It sounds like you're calling that before the API call finishes. Commented Feb 22, 2017 at 17:57
  • @krillgar Kindly advice on a better way to do it...I can't even tell the best way to Commented Feb 22, 2017 at 18:02

1 Answer 1

2

The endpoint replies with object that does not include rovers. However, it includes : id, userId, title and body


enter image description here


That's why response.rovers is undefined. Then this.state.rovers is the same

So , you might mean 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')
   });
 });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Congrats 🎉 .. You are Welcome👋 @wallraks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.