Fetching data from API endpoint

Hi guys!

I have a quick question regarding fetching data from an API in React.
I’m fetching data from ‘https://jsonplaceholder.typicode.com/users’.
I simply want to display the name’s of the users, no other information.

Here is my code in React…

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

    this.state = {
      people: []
    }
  }

componentDidMount() {
  fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => response.json())
  .then(users => this.setState({ people: users }))
}

  render() {
  return (
    <div className="App">
      {this.state.people.map(person => (
      <h1 key={person.id}> {person.name} </h1>
      ))}
    </div>
  );
}
}

It works fine…but I don’t understand why.
How does it know that I only want the name of the user, and not all the other information? Or for example, if I want only the email address, how do I specify this?
I understand that fetch() is calling the API.
It returns a promise in the form of a response which I then convert to json format.
At this stage if I console.log the response I have an array which contains objects of many properties (name, email, address etc).
then final line I don’t understand…

.then(users => this.setState({ people: users }))

How does it know that users should refer to just the name property? What if I want the email address instead? Or multiple properties?

Thanks!

Hi @ollyb. It doesn’t know. You are the one telling it in your code.
In .then(users => this.setState({ people: users })), you are setting the users you have fetched as the value of people in this.state.
Actually if you do console.log(this.state.people) inside render method just before return you will see your “people” with all the properties. Essentially you are returning:

<div className="App">
      {this.state.people.map(person => (
      <h1 key={person.id}> {person.name} </h1>
      ))}
</div>

You are rendering person.name inside h1 tag leaving all the other properties in this.state.people. If you want to render the other values you can as well render them.

1 Like

Thank you nibble, that makes perfect sense. I managed to ignore everything inside the render method :slight_smile:

Thanks again :+1:

1 Like