0
import React, { Component } from 'react';

export class FetchData extends Component {
  static displayName = FetchData.name;

  constructor(props) {
    super(props);
    this.state = { users: [], loading: true };
  }

  componentDidMount() {
    this.populateUserData();
  }

  static renderUsersTable(users) {
    return (
      <table className='table table-striped' aria-labelledby="tabelLabel">
        <thead>
          <tr>
            <th>Username</th>
            <th>Likes</th>
            <th>Image Url</th>
          </tr>
        </thead>
        <tbody>
          {users.map(id =>
            <tr key={id.user}>
              <td>{id.username}</td>
              <td>{id.likes}</td>
              <td>{id.imageUrl}</td>
            </tr>
          )}
        </tbody>
      </table>
    );
  }

  render() {
    let contents = this.state.loading
      ? <p><em>Loading...</em></p>
      : FetchData.renderUsersTable(this.state.users);

    return (
      <div>
        <h1 id="tabelLabel" >API info</h1>
        <p>This component demonstrates fetching data from the api.</p>
        {contents}
      </div>
    );
  }

  async populateUserData() {
    const response = await fetch('http://api.myjson.com/bins/1ge417');
    const data = await response.json();
    this.setState({ users: data, loading: false });
  }
}

Why isn't my JavaScript code returning any data from the JSON API ? I have specified an Array type, and it still doesn't return anything. Any help/correction will be appreciated!

P.S. This is a template which I'm using from "dotnet new react -o my-new-app"

5
  • Still doesn't work :/ Commented Nov 5, 2019 at 9:34
  • where's your error handling? perhaps there's an error Commented Nov 5, 2019 at 9:34
  • Its good practice to use a trycatch block or something similar for error handling Commented Nov 5, 2019 at 9:37
  • what is the format of the incoming data ... an example would help Commented Nov 5, 2019 at 9:38
  • let contents ==== this.state.loading Commented Nov 5, 2019 at 9:44

2 Answers 2

1

The problem is in your map-function. You need to extract the id as key, the user which holds the actual user-information and the post for the likes and the imageUrl:

import React, { Component } from 'react';

export class FetchData extends Component {
  static displayName = FetchData.name;

  constructor(props) {
    super(props);
    this.state = { users: [], loading: true };
  }

  componentDidMount() {
    this.populateUserData();
  }

  static renderUsersTable(users) {
    return (
      <table className='table table-striped' aria-labelledby="tabelLabel">
        <thead>
          <tr>
            <th>Username</th>
            <th>Likes</th>
            <th>Image Url</th>
          </tr>
        </thead>
        <tbody>
          {users.map(({id, user, post}) =>
            <tr key={id}>
              <td>{user.username}</td>
              <td>{post.likes}</td>
              <td>{post.imageUrl}</td>
            </tr>
          )}
        </tbody>
      </table>
    );
  }

  render() {
    let contents = this.state.loading
      ? <p><em>Loading...</em></p>
      : FetchData.renderUsersTable(this.state.users);

    return (
      <div>
        <h1 id="tabelLabel" >API info</h1>
        <p>This component demonstrates fetching data from the api.</p>
        {contents}
      </div>
    );
  }

  async populateUserData() {
    const response = await fetch('http://api.myjson.com/bins/1ge417');
    const data = await response.json();
    this.setState({ users: data, loading: false });
  }
}

take a look at your json:

[
    {
        "id": 1,
        "user": {
            "username": "Ola Nordmann",
            "profileImageUrl": "https://randomuser.me/api/portraits/men/43.jpg"
        },
        "post": {
            "text": "En post-tekst!",
            "likes": 123,
            "imageUrl": "https://picsum.photos/id/1023/500/500"
        }
    },
    {
        "id": 2,
        "user": {
            "username": "Kari Nordmann",
            "profileImageUrl": "https://randomuser.me/api/portraits/men/42.jpg"
        },
        "post": {
            "text": "Sjekk bildet mitt!",
            "likes": 233,
            "imageUrl": "https://picsum.photos/id/1018/500/500"
        }
    },
    {
        "id": 3,
        "user": {
            "username": "Henrik Wergeland",
            "profileImageUrl": "https://randomuser.me/api/portraits/men/41.jpg"
        },
        "post": {
            "text": "Meget posei!",
            "likes": 300,
            "imageUrl": "https://picsum.photos/id/1002/500/500"
        }
    }
]
Sign up to request clarification or add additional context in comments.

1 Comment

It worked, but it is only displaying a name, why is that?
0

Can you please use SSL URL. If your application is running on https then your API should be in https.

I guess that's the problem for you. Can you update below line in your code and check it.

const response = await fetch('https://api.myjson.com/bins/1ge417'); // use https instead of http

Hope this will work for you!

Here have created demo for you. https://stackblitz.com/edit/react-wd8o27

Comments

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.