Day 5: Making server request in React with Axios
#100DaysOfCode : Building a React App: Completion
Project (2 Hours): Introduce HTTP network requesting capability in the app using Axios to make github API calls. Create search menu, display user bio and repos component with data retrieved from server. Wrap up all components together to complete the build out of this React App!
All the code for this project can be found on my github.
Step 1: Create a search menu
This is a fairly simple step with creation of a static menu bar with a textbox and search button that is displayed up top at all times. We pushState of the textbox contents using the react mixin “history”.
handleSubmit: function(){
var username = this.usernameRef.value;
this.usernameRef.value = ‘’;
this.history.pushState(null, “//profile/” + username)
}
Step 2: Install Axios to make promise based HTTP or network request
We use Axios for getting github profile and repo info using github HTTP request API. This is very similar to $HTTP in Angular.
npm install — save axios
Make a helper utility that would let you make promise based network requests.
Promise based request means if we invoke “getRepos” function above, it returns a promise object. This promise object has a “.then” property which is used as a callback function to be invoked when promise object gets resolved.
var promiseObj = getRepos(‘test’);
promiseObj.then(function(data){
console.log(‘data’);
});
We can also use “axios.all” to chain together to wait on a group of promise objects and callback a function only when all requests are returned.
Step 3: Finally render out the repos and bio in respective components using a list index. Full code for this can be found in my github.
In the Repos.js, we add a list item when it has a “html_url” and “html_description” property available as below. Similarly we verify and create Bio.js component with pic, blog, location etc.
<li className=”list-group-item” key={index}>
{repo.html_url && <h4><a href={repo.html_url}>{repo.name}</a></h4>}
{repo.description && <p>{repo.description}</p>}
</li>
Once everything is tied together and webpack is run, we should finally have our completed React App with searchable menu that displays github bio and repo components (made possible with Axios) as well as a note taking capability that is persisted to firebase. Final app looks like below.
Day 5 of #100DaysOfCode DONE
Also, please click 👏 so that others can enjoy it as well. Follow me on Twitter @HariniLabs to get the latest updates or just to say Hi :)
PS: I curate a bi-weekly #WomenInTech newsletter for a dose of inspiration from the world of tech and yes men can signup too! Get it here :)