< Previous: Cleaning up and Preparing for a Real Project | Next: Converting GitHub's JSON into Meaningful JSX > |
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.
Add this method to your component:
src/pages/Detail.js
componentWillMount() {
ajax.get('https://api.github.com/repos/facebook/react/commits')
.end((error, response) => {
if (!error && response) {
this.setState({ commits: response.body });
} else {
console.log('There was an error fetching from GitHub', error);
}
}
);
}
Let's break down what it actually does…
body
value of the SuperAgent response.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!
< Previous: Cleaning up and Preparing for a Real Project | Next: Converting GitHub's JSON into Meaningful JSX > |
Copyright ©2016 Paul Hudson. Follow me: @twostraws.