1
votes

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?

1
Try to print to console data in then() handler to make sure that data actually fetched. - oklas
Perhaps setting the value of swag in the constructor to an empty array []. this.state = { swags: [] }; - It'sNotMe
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 - Quentin

1 Answers

4
votes

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' })
})