Kelly codes
Kelly codes

Reputation: 7

React js Pull Data from url

I'm trying to get my code to display the user data from the const url for ex. "name" and "username". However, nothing is showing for me when I try to preview it in my local environment. Can someone help me with the code to get this to work. Thank you.

import React from "react";

export default class FetchRandomUser extends React.Component {
  state = {
    loading: true,
    person: null
  };

  async componentDidMount() {
    const url = "https://jsonplaceholder.typicode.com/users";
    await fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((myJson) => {
      console.log(JSON.stringify(myJson));
      //First check what type of data you are getting here and then try to set your state as below.
      this.setState({person:myJson, loading:false});
    })
    .catch(error => console.error(error)); //If error occurs you will get here
  }
     
  render() {
    if (this.state.loading) {
      return <div>loading...</div>;
    }

    if (!this.state.person) {
      return <div>didn't get a person</div>;
    }

    return (
      <div>
        <div>{this.state.id}</div>
        <div>{this.state.name}</div>
        <div>{this.state.username}</div>
      </div>
    );
  }
}

Upvotes: 0

Views: 108

Answers (1)

Prateek Thapa
Prateek Thapa

Reputation: 4938

Because the API (fetch request) returns an array of objects, an array of a person not a single person. You need to use map to iterate over single item in your array.

Also, rename your state variable to persons not person. It is a better practice to name your variable plural if it represents an array

import React from "react";

export default class FetchRandomUser extends React.Component {
  state = {
    loading: true,
    persons: null
  };

  async componentDidMount() {
    const url = "https://jsonplaceholder.typicode.com/users";
    await fetch(url)
      .then(response => {
        return response.json();
      })
      .then(myJson => {
        console.log(JSON.stringify(myJson));
        //First check what type of data you are getting here and then try to set your state as below.
        this.setState({ persons: myJson, loading: false });
      })
      .catch(error => console.error(error)); //If error occurs you will get here
  }

  render() {
    if (this.state.loading) {
      return <div>loading...</div>;
    }

    if (!this.state.persons) {
      return <div>didn't get a person</div>;
    }

    return (
      <div>
        {this.state.persons.map(person => {
          return (
            <>
              <div>{person.id}</div>
              <div>{person.name}</div>
              <div>{person.username}</div>
            </>
          );
        })}
      </div>
    );
  }
}

Upvotes: 1

Related Questions