0

I am new to react and working on some exercises. Inside YTSearch when I am using this, i get a message that this is undefined. But the tutorial instructor which i am looking at has the same code and it is working for him. Can someone help?

import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import YTSearch from 'youtube-api-search';

const API_KEY = "AIzaSyCDclF-xo-YjMt48H8WMsnebncKmU3jsQA";

class App extends Component {
    constructor(props){
        super(props);
        this.state = { 'videos' : []};
        YTSearch({ key: API_KEY, term: 'surfboards'}, function(data){
            console.log(data);
            console.log(this);
        });
    }

    render(){
        return <input />;
    }
}

ReactDOM.render(<App />, document.querySelector('.container'))

1 Answer 1

1

Its a context issue, you forgot to bind the callback method, to use this keyword, you need to bind it, use this:

   constructor(props){
        super(props);
        this.state = { 'videos' : []};
        YTSearch({ key: API_KEY, term: 'surfboards'}, function(data){
              console.log(data);
              console.log(this);
           }.bind(this)
        );
    }

or use arrow function it will do this job for you, you don't need to worry about method binding, use this:

       constructor(props){
            super(props);
            this.state = { 'videos' : []};
            YTSearch({ key: API_KEY, term: 'surfboards'}, (data)=>{
                  console.log(data);
                  console.log(this);
            });
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.