Fetching Ajax Data from GitHub using SuperAgent

Part of the reason I enjoy working with SuperAgent is that it's so very simple to use – the creators did a great job in making its methods easy to read and understand. To get started, import SuperAgent into your component like this:

src/pages/Detail.js

import ajax from 'superagent';

Note: you can call SuperAgent whatever you want in your code, and their own examples usually alias it as request rather than ajax. I find ajax easy to remember, which is why I use it.

Now, we want our Ajax call to run when our page loads, and React has a special method that gets called at just the right time: componentWillMount(). As you can probably guess from the name, this method gets called on a component just before it's rendered for the very first time. This makes it a great place for us to kick off our Ajax request.

.end((error, response) => { tells SuperAgent what to do when the request finishes: it should run the anonymous function that follows.

if (!error && response) { starts a conditional statement: the following should run only if there was no error and there was a response from the server.

this.setState({ commits: response.body }) updates our component's state using the body value of the SuperAgent response.

} else { the other half of our conditional statement: if there was an error or if the server provided no response.

console.log(...) print an error message to the browser console window.

Lots of closing braces.

There are two more things you need to know in order to understand that code. First: all SuperAgent calls are asynchronous, which means your code doesn't just freeze while SuperAgent waits for GitHub to respond. Instead, other code executes, and SuperAgent will only call your anonymous function when it has finished getting GitHub's response.

The second thing to know is that response.body is a bit of SuperAgent magic: it has detected that GitHub has responded with the content type "application/json" and automatically converts GitHub's response into JavaScript objects. That's why we can send response.body straight into our state: it's already an array of objects ready to use.

When you save your page now, you'll see "Some commit data here" printed out lots of times in your browser. Each of those is the result of one commit to the Facebook GitHub repository, but we're not doing anything with each commit just yet – our JSX is static.

Buy the book for $10

Get the complete, unabridged Hacking with React e-book and take your learning to the next level - includes a 45-day no questions asked money back guarantee!

If this was helpful, please take a moment to tell others about Hacking with React by tweeting about it!