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!