MegaRacer MegaRacer - 4 years ago 98
React JSX Question

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 !

Answer Source

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}))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download