1

There is a simple API on URL localhost:3001/swags with a few items and now I want to display them in a very simple REACT APP.

This is my REACT APP:

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      swags: null
    };
  }

  componentDidMount() {
    fetch('http://localhost:3001/swags')
      .then(response => response.json())
      .then(data => this.setState({ swags: data }));
  }

  render() {        
    return (
      <div><pre>{JSON.stringify(this.state, null, 2) }</pre></div>
    );
  }
}

export default App;

The Output on localhost:3000 ist an empty Object

{
  "swags": null
}

postman show me this output under this URL http://localhost:3001/swags

[
    {
        "id": 1,
        "title": "Item 1",
        "description": "Lorem ipsum dolor sit amet"
    },
    {
        "id": 2,
        "title": "Item 2",
        "description": "sed diam nonumy eirmod tempor"
    },
    {
        "id": 3,
        "title": "Item 3",
        "description": "takimata sanctus est Lorem ipsum dolo"
    }
]

Can anyone explain why the output of my simple App ist an empty object?

3
  • Try to print to console data in then() handler to make sure that data actually fetched. Commented Aug 8, 2019 at 9:36
  • Perhaps setting the value of swag in the constructor to an empty array []. this.state = { swags: [] }; Commented Aug 8, 2019 at 9:37
  • 1
    Start by debugging in the browser. Use the Developer tools. Look at the Console. Are there errors? Look at the Network tab, are the request and response exactly as you expect? Dollars to doughnuts says this is another duplicate of stackoverflow.com/a/35553666/19068 Commented Aug 8, 2019 at 9:49

1 Answer 1

4

As per your code. The page will first render with swags: null and then it will make a call to http://localhost:3001/swags. If your request succeeds you will get the response on the screen. If you value on screen is not changing it means something is wrong in the API call. You can add a catch block or you can print the value inside final then to check if everything is right or not.

fetch('http://localhost:3001/swags')
.then(response => response.json())
.then(data => {
    console.log(data) // Check the value of data in console
    this.setState({ swags: data })
})
.catch(err => {
    console.log(data) // Check if error in console
    this.setState({ swags: 'API Failed' })
})
Sign up to request clarification or add additional context in comments.

1 Comment

This answer was helpful, with the console Output I can debug the API Call and see that the Error only was a restriction issue.

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.