React and AJAX

React and AJAX

Recently I made the new Staytube website in React and needed to make Ajax-requests. The question was how? And what is the “right” or “preferred” way? The answer is it depends: Depends on the size of your app, the complexity of your app, on the tools you’re using..

Being a React beginner myself, I went for a fairly simple approach (without Flux/Redux), but thought I would make a little writeup.

YouTube as CMS

Staytube is a simple website dedicated to great full length concerts from YouTube. I’m exploring the concept on “Using YouTube as CMS”. The website is communicating with a playlist on YouTube, making requests using the YouTube V3 API. You will need an API-key for making calls to the playlist API.

React

AS you may know React is view library and has no built in networking features. React renders components, using data from props and state. If you want to use some data from the server, you need to get that data into your components’ props or state.

For making Ajax calls you will need to use a http/xhr library. I dediced to use Axios, a promised based http client.

Other tools you could use:

Install Axios

npm install axios --save

Settting the initial state

In React you can define initial state by assigning this.state in the constructor. Read more about initial state

class LatestVideos extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      error: false,
      videos: [],
      nextpagetoken: '',
      prevpagetoken: '',
    };
    this.fetchVideos = this.fetchVideos.bind(this);
    this.nextPage = this.nextPage.bind(this);
    this.prevPage = this.prevPage.bind(this);
  }

  /* … */

Go get some videos

Ok, so I have a playlist and need to get some videos from it. The URL for fetching my playlist looks like this:

https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=30&pageToken=XXXXXXXXXXXXXXXXXX&playlistId=PLUIjiNV9YTmsGucmZPzRrVR1GSlmRQ6pk&key=XXXXXXXXXXXXXXXXXX&alt=json;

Mounting

I’m using the componentDidMount life cycle method. This method will be executed when the component “mounts” (added to the DOM) for the first time. This method is only executed once during the component’s life. Read more about React life cycle methods.

I have a component responsible for fetching and listing recent videos in my playlist. A bit simplified in this example, but in short it looks like this.


/* … */

componentDidMount() {
  this.fetchVideos();
}
fetchVideos(direction) {
  this.setState({
    loading: true,
  });

  const url = `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=30&pageToken=${token}&playlistId=PLUIjiNV9YTmsGucmZPzRrVR1GSlmRQ6pk&key=${apikey}&alt=json`;
  axios.get(url)
    .then(res => {
      this.setState({
        videos: res.data.items,
        loading: false,
      });
    })
    .catch(error => {
      console.log(error);
    });
}

/* … */

Render

Now this component is responsible for rendering the list of videos, using their static thumbnails associated with every YouTube video.

renderVideos() {
  return this.state.videos.map((video, index) => {

    const videoClip = video.snippet.resourceId.videoId;
    const image = 'https://placehold.it/480x360';
    const alt = video.snippet.title;

    if (video.snippet.hasOwnProperty('thumbnails')) {
      image = video.snippet.thumbnails.high.url;
    }

    return (
    	<div key={ index }>
    		<Link to={ `/videos/${videoClip}` }>
    			<img src={ image } role="presentation" alt={ alt } />
    			<p>
    				{ alt }
    			</p>
    		</Link>
    	</div>
    );
  });
}
render() {
  return (
    <div>
      { this.state.loading ? <div className="loader"></div> : this.renderVideos() }
   	</div>
    )
}

🤔 Need something more in-depth?

Andrew H Farmer wrote an excellent post “React AJAX Best Practices” where he explaines four good ways of doing Ajax-requests with React.


Demo?

💥 Check out Staytube! The code is on Github if you want to know more.