I'm just starting to learn ES6 & ReactJS coming from a ES5 background.
I've been scratching my head with this ES6 code.
Code#1:
class App extends Component {
constructor(props) {
super(props);
this.state = { videos: [] };
YTSearch({key: API_KEY, term: 'surfboard'}, function(data) {
this.setState({ videos: data }); **//I GET AN ERROR HERE!!**
});
}
render() {
return (
<div>
<SearchBar />
</div>
);
}
}
I get an error
in this.setState
bundle.js:19826 TypeError: Cannot read property 'setState' of undefined(…)
But, if I do
Code#2:
YTSearch({key: API_KEY, term: 'surfboard'}, (data) => {
this.setState({ videos: data }); **//I GET AN ERROR HERE!!**
});
This works fine.
I can understand in first case, the scope of this
in a general function
is different in a callback (like AJAX). But how does that change in example #2?