React Call Youtube on Exit of Input

Im trying to use youtubes API with the you-tube-api search library, but am having some trouble getting new searches to happen.

I created a new function called search_youtube that I want to be called when a user exits the input. The way I have it setup now, the function is called continuously when I load the html page.

What is the appropriate way to solve this so that when a user exits the input a new search is rendered.

class SearchBar extends Component {
  constructor(props) {
    super(props)

    this.state = {
          videos: [],
          selectedVideo: null
        }
  }

  searchYoutube(event) {
    console.log("called")
    YTSearch({ key: API_KEY, term: event.target.value }, (videos) => {
      this.setState({
        videos: videos,
        selectedVideo: videos[0]
      })
    });
  }

  render() {
    return(
      <div className="search-bar">
        <input onBlur={this.search_youtube(event)} />
      </div>
    )
  }
}

1 answer

  • answered 2017-06-17 18:50 Yuri Ramos

    They are loading everytime you load your page because it's inside your render function, you are calling that function instead of passing the function to onBlur, change that line to this:

      <input onBlur={event => this.search_youtube(event)} />
    

    Obs. If you want to learn more about arrow functions check this article.