0

I'm new in React development.. this is the code I've wrote

constructor(props) {
    super(props);

    this.state = { videos: [] };
    YTSearch({ key: API_KEY, term: 'Led zeppelin'}, function(videos) {
        this.setState({ videos });
    });
}

but when running i've this error into the console

proxyConsole.js:56 TypeError: Cannot read property 'setState' of undefined
    at index.js:17
    at index.js:19
    at <anonymous>

the "this" variable is null.. why? How can i access to this.setState ??

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Mimmo
  • 113
  • 1
  • 16
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Yury Tarabanko Aug 10 '17 at 10:05
  • binding issue use arrow function `(videos) => {`, check this ques also: [Cannot read property 'setState' of undefined](https://stackoverflow.com/questions/32317154/uncaught-typeerror-cannot-read-property-setstate-of-undefined) – Mayank Shukla Aug 10 '17 at 10:06
  • Right.. thank you very much – Mimmo Aug 10 '17 at 10:12

1 Answers1

1
 YTSearch({ key: API_KEY, term: 'Led zeppelin'}, (videos) => {
        this.setState({ videos });
    });

Try this

Nocebo
  • 1,927
  • 3
  • 15
  • 26