How to Call API in React.js Using Axios (Real Life Example)

API’s are everywhere these days. For Data, Calculations, Analysis and for other variety of things we use them. Let’s see how to call API in React.js. Normally, we can do this with fetch API call of JavaScript. But there is a better way to call API in React using Axois library.

Requirements:

  • Visual Studio Code
  • Node.js
  • create-react-app
  • Axois
  • Basic JavaScript and React.js Knowledge

For this tutorial, we expect that you know how to setup create-react-app.

In this Real Life Example, we are going to use Github Users API. We will create a Form where we can put a GitHub username and after clicking on “Add User” button it will call API and add that user to the list. Here is the final output of this small application looks like.

You will find all code in GitHub Repository.

Call API in React.js Using Axios

Components Used in the Application

1] Card Card component is used to display Profile Picture, Name and Company of the user.

2] CardList – Obviously, when you need to display multiple users profiles at the same time, you need Array to hold them. The CardList component makes the array of Card components. CardList is parent component to Card component because it consists Card component inside it or also we can say, it renders Card component.

3] Form Form component consists of text input and button elements. Also, it contains click handler event for button.

4] App – This is the final and most important component because it contains all the other components in it. All above mentioned components are child to this.

Let’s see Code for all the above components:

Card Component (App.js)

‎
function Card(props) {
  const profile = props;
  return (
    <div className="github-profile">
      <img src={profile.avatar_url} />
      <div className="info">
        <div className="name">{profile.name}</div>
        <div className="company">{profile.company}</div>
      </div>
    </div>
  );
}
‎

Props contains single profile data which came from API and being displayed in the Card component. We are storing that data into local variable called ‘profile’. It contains single user information which is to be displayed.

CardList Component (App.js)

‎
function CardList(props) {
  return (
    <div>
      {props.profiles.map(profile => <Card {...profile} />)}
    </div>
  );
}
‎

CardList components accepts Props, in which it contains the ‘profiles’ array. The array contains multiple users information we have added in it. We are using JavaScript map function to loop through all the users inside ‘profiles’ array and pass one-by-one user to the Card components as props.

Form Component (App.js)

‎
function Form(props) {

  const [userinput, changeValue] = useState('');


  async function handleSubmit(event) {
    event.preventDefault();
    const res = await axios.get(`https://api.github.com/users/${userinput}`);
    props.onSubmit(res.data);
    const clean = () => changeValue('');
    clean();
  }


  return (
    <div>
      <div style={{textAlign:"center", fontWeight:"bolder", fontSize:30}}> Add GitHub Users:</div>
      <br/>
      <form onSubmit={handleSubmit}>
        <input type="text"
          value={userinput}
          placeholder="GitHub UserName..." required
          onChange={(e) => changeValue(e.target.value)}
        />

        <button>Add User</button>
      </form>
    </div>
  );
}
‎

In the Form component, lets start from return part. In that, we are returning header of application “Add GitHub Users:”. Also we are rendering a Form element. Form contains text input and the button. If you look at the text input we are controlling its state using react useState().

Note: There is default state of input text which is controlled by DOM but we are overriding (it is entirely not overriding but using both Default and React state combined) it by using the concept called “Controlled Component“.

We are using form’s onSubmit event to call submit click handler (handleSubmit).

Now here you need Axios. Go to the Terminal in Visual Studio Code and type below command and hit enter. Before entering command make sure path is set to application your are creating.

$ npm install axios

Now you can use axios library in your application. You can see in code that we have called get method of axois and passed GitHub API url to it. In the URL user should be dynamic so {userinput} we are passing as dynamic value. To use dynamic value in staring you need to use backtick(`) to enclose URL (or string).

By using props.onSubmit we are calling function updatedprofiles inside App component to update the state of array. We will talk about updatedprofiles function when we discuss about App component. We are passing user data to updatedprofiles function as parameter via onSubmit props.

At the end of handleSubmit function we are clearing the value from the text input.

App Component (App.js)

‎
function App() {

  const [userprofiles, addprofile] = useState([]);

  const updatedprofiles = (profiledata) => addprofile([...userprofiles, profiledata]);


  return (
    <div>
      <Form onSubmit={updatedprofiles} />
      <CardList profiles={userprofiles} />
    </div>
  );
}
‎

This is the main component where all magic happens. Important work of App component is to provide access to Array’s state to both Form and CardList components.

Form component wants to add new user to the Array and CardList component needs to display list. That’s why Array can’t be created in Form component and manage it’s state there, because then its state would not be available for CardList component.

Component state is always private for that component only unless it has child component.

Some of you may argue that the CardList component can be added to Form component. But as per single responsibility principle it wouldn’t be a good idea. CardList component is there to display list only. It doesn’t matter for CardList component what is happening inside Form component.

In the app component you can see we have created blank array (userprofiles) by using useState to manage its state. Function addprofile is basically there to update the state of array.

updatedprofiles is just a refence to the function addprofile.

We have passed updatedprofiles function’s reference as props to the Form component. Form component is also passing user data as parameter to updatedprofiles function.

Basically Form component is able to call function inside App component because it is child to App component and props can flow in both directions (Parent to Child and Child to Parent). You can see its a two way data flow passing because of props.

When there is submit activity inside Form component, it will pass data it has collected and also call the function in App component.

When updatedprofiles gets called by Form component it automatically calls addprofile function which takes user data as parameter from Form component. The addprofile function updates array (userprofiles) with new user data.

At the end of the App component we are passing ‘profiles’ props to the CardList component which ultimately takes array of userprofiles.

The CardList component receives updated array through props and it displays the new list.

All the above components are part of App.js file. You can create separate file for each components too as per your design requirements.

Working Code

App.js

‎
import { useState } from "react";
const axios = require('axios').default;

function CardList(props) {
  return (
    <div>
      {props.profiles.map(profile => <Card {...profile} />)}
    </div>
  );
}

function Form(props) {

  const [userinput, changeValue] = useState('');


  async function handleSubmit(event) {
    event.preventDefault();
    const res = await axios.get(`https://api.github.com/users/${userinput}`);
    props.onSubmit(res.data);
    const clean = () => changeValue('');
    clean();
  }


  return (
    <div>
      <div style={{ textAlign: "center", fontWeight: "bolder", fontSize: 30 }}> Add GitHub Users:</div>
      <br />
      <form onSubmit={handleSubmit}>
        <input type="text"
          value={userinput}
          placeholder="GitHub UserName..." required
          onChange={(e) => changeValue(e.target.value)}
        />

        <button>Add User</button>
      </form>
    </div>
  );
}

function Card(props) {
  const profile = props;
  return (
    <div className="github-profile">
      <img src={profile.avatar_url} />
      <div className="info">
        <div className="name">{profile.name}</div>
        <div className="company">{profile.company}</div>
      </div>
    </div>
  );
}

function App() {

  const [userprofiles, addprofile] = useState([]);

  const updatedprofiles = (profiledata) => addprofile([...userprofiles, profiledata]);


  return (
    <div>
      <Form onSubmit={updatedprofiles} />
      <CardList profiles={userprofiles} />
    </div>
  );
}

export default App;
‎

index.js

‎
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();
‎

index.html

‎
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="Web site created using create-react-app" />

    <title>React App</title>
  </head>

  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>

</html>
‎

index.css

‎
.github-profile {
	margin: 1rem;
}

.github-profile img {
  width: 75px;
}

.github-profile .info {
  position: absolute;
  display: inline-block;
  margin-left: 12px;
}

.github-profile .info .name {
  font-size: 1.25rem;
  font-weight: bold;
}

form {
	border: thin solid #ddd;
  background-color: #fbfbfb;
  padding: 2rem;
  margin-bottom: 2rem;
  display: flex;
  justify-content: center;
}

.header {
	text-align: center;
  font-size: 1.5rem;
  margin-bottom: 1rem;
}
‎

That’s it. We hope that you will able to create this small application of your own now. Also, if you want to make any changes to original application then you are free to make changes to it in GitHub repository mentioned above. You can add more functionality to it to learn and contribute.