HalfWebDev
HalfWebDev

Reputation: 7648

Understanding of code in fetch call reactjs

I am having trouble to relate to the last line in code below

componentWillMount(){
fetch( 'https://swapi.co/api/people/?format=json' )
  .then( response => response.json() )
  .then( ({results: items}) => this.setState({items}))
}

The last thenable has {results: items} and then it sets or assigns the {items : items }if interpreted in es5 way. But I can't relate to the way the arguments are put up in thenable.

Why we just can't do

.then( (items) => this.setState({items}))

Please advise !

Upvotes: 1

Views: 34

Answers (1)

Jayce444
Jayce444

Reputation: 9073

Well it looks like in your response there is a object called 'results' and you want to set the 'items' object in your state to that. So if you just said

.then( (items) => this.setState({items}))

it would look for the 'items' object and set THAT to the items object in state. However, the object in your response isn't called 'items', it's called 'results'. So first it is re-labelled from results to items, then that is used as the argument. So:

.then( ({results: items}) => this.setState({items}))

is the same as

.then( ({results}) => this.setState({items: results}))

Upvotes: 1

Related Questions