back to all posts

Refactoring Youtube Player to use Flux — Part 2

by Nabendu Biswas / April 25th, 2018

#react #javascript #flux
Series: Youtube-Player-React

Welcome to Part 2 of the Flux series. Now we will add the SearchBar functionality. It is pretty much straight forward. First update the App.js to include SearchBar as below.

Update App.jsUpdate App.js

Now, update the search_bar.js . It’s only a minor update and we have added the YTSearchAction() in our onInputChange() and passing the

Update search_bar.jsUpdate search_bar.js

No, other thing needs to be changed and our change is already reflected as the ytSearch_actions.js will take the new searchTerm and do the youtube-api-search. It gets passed to the ytSearch_store.js and then to video_list_item.js to be displayed. Notice, earlier we were triggering the action from App.js with a string ‘React tutorial’. Following exactly the same process here with search_bar.js

Updated site with Search capabilitiesUpdated site with Search capabilities

Now, we will show the youtube player by working on video_detail.js . First let add the component to App.js

Adding VideoDetailAdding VideoDetail

We will then add a function getFirstVIdeo() in ytSearch_store.js to return the first video instead of the whole array of object. We are doing this because when the apps load for the first time and the initial youtube search on “React Tutorials” is triggered, we want to display the first video instead of blank.


Now, we will update the video_detail.js. You will see the pattern is almost similar to video_list_item.js , where also we register to the store and have these react lifecycle methods.

updated video_detail.jsupdated video_detail.js

Here in the constructor, we have a state object item. We initialise it with YTSearchStore.getFirstVIdeos(). But this will receive a undefined, because the youtube-search-api takes 1–2 sec to get the videos and React renders this component by this time. Try commenting out below -

    if (!this.state.item) {
        return <li className="media-right">Loading…</li>;

And you will get the classic react undefined error -

undefined errorundefined error

Rest flow is similar to video_list_item.js and we will get this output in our page.

Updated AppUpdated App

This concluded Part 2 of the series. In Part 3 we will add the select functionality to select a video, by clicking on right side list.

Nabendu Biswas