I was learning ReactJS here: https://egghead.io/lessons/react-dynamically-generated-components and came across this code snippet:
componentWillMount(){
fetch( 'http://swapi.co/api/people/?format=json')
.then( response => response.json() )
.then( ({results: items}) => this.setState({items}) )
}
What does the ({results: items}) part of the arrow function mean?
I've seen arrow function
()=>console.log('hi')word=>console.log(word)(one, two)=>console.log(one)But never an object literal in this way.
Also, why does this.setState({items}) need curly braces around items? What does it all mean?
this.setState({items})
is ES6 shorthand for
this.setState({items: items})
and
({results: items})
basically accepts an object as a parameter with the property named results, and in the function body this is mapped to items
run trhough a transpiler, e.g. babel try it out repl page your code
fetch( 'http://swapi.co/api/people/?format=json')
.then( response => response.json() )
.then( ({results: items}) => this.setState({items}) )
becomes
var _this = this;
fetch('http://swapi.co/api/people/?format=json')
.then(function (response) {
return response.json();
})
.then(function (_ref) {
var items = _ref.results;
return _this.setState({ items: items });
});
I would recommend keeping a link to that babel page - if any ES6 code confuses you, paste it there to see what the ES5 version is :p that's my cheat