Using HTTP client Axios in a React Application featured image

Using HTTP client Axios in a React Application: A Tutorial

Many web apps face the necessity of interfacing with a REST API at some point in their development. For React-based web apps, we can use Axios, a lightweight HTTP client based on the $http service within Angular.js v1.x. The features are similar to JavaScript’s native Fetch API.

Axios is promise-based, allowing us the ability to incorporate JavaScript’s async and await for more readable synchronous code. It also supports intercept and request cancellation. Moreover, there’s built-in client-side protection against cross-site request forgery.

In this guide, we will showcase how to use Axios to access the popular JSON Placeholder API in a demo React application. You can learn more about the JSON format in JavaScript from this tutorial.

Prerequisites

To complete the steps demonstrated in this guide, you’ll need the following components:

Step 1: Install Axios in the React Project

Axios is directly available as an npm module. Check out Axios on npm. All we need is to establish a React project and install the Axios package.

The following npx command will run create-react-app to create a new React project. The project name will be used to create a dedicated directory for the project. Here, we named the project react-axios-demo. Run the command:

Change the current directory to the newly-created project directory:

Next, invoke the npm install command to install Axios. If no version is specified, then npm will automatically download and install the latest version of Axios:

Our project is now ready to use Axios! It’s time to put its features into action.

Step 2: Construct a GET Request

In this step, we will showcase creating a new component that uses Axios to send a GET request.

First, create a new component PersonList that will show a list of names. Create a dedicated directory to store the component:

Next, create the file PersonList.js :

Open the file in a text editor. We are using Visual Studio Code for comfort and readability. Enter the following JavaScript code:

 

Here:

  • We’ve imported React and Axios so that we can use them both in the component.

  • We hook into the componentDidMount lifecycle hook and send a GET request.

You can use axios.get(<url>) from an API endpoint to get a promise (returns a response object). Within the response object, it contains the desired data. We then assign it to the value of person. We can also gather additional info about the request, like status code under res.status or further info from res.request.

Next, we need to add our component to the main App.js file. Add the following codes:

 

The configuration is complete for the step. You can now run the app and test it using your favorite browser. Start the development server:

Axios React code screenshot 1

As we can see, the output shows a list of people’s names in random order:

Step 3: Construct a POST Request

In this section, we will showcase using Axios to perform another HTTP request method called POST. To demonstrate this, our goal is to create a new component to our React project named PersonAdd.

Create the file PersonAdd.js:

Axios React code screenshot 2

Then, open the file in a text editor and enter the following code:

Axios React code screenshot 3

In this code, we’re taking user input and POSTing the content to an API. Inside the handleSubmit function, we’re preventing the default action of the form and updating the state to the user input. When using POST it returns the same response object. We can use the object inside of a then call. To fulfill the POST request, we’re capturing the user input and adding it along with the POST request. It gives us a response. We’re logging the response using console.log. It should show the user input in the form.

Next, add the component to App.js. The full code should look like this:

Axios React code screenshot 4

Now, time to test the changes. Start the development server:

Check the change on the web browser:

Axios React code screenshot 5

Step 4: Construct a DELETE Request

In this section, we will demonstrate deleting items from an API with the help of axios.delete and using a URL as the parameter. To demonstrate, create the component PersonRemove. Create the file PersonRemove.js in the src/components directory:

Axios React code screenshot 6

After that, open the file in a text editor and add the following code:

Axios React code screenshot 7

Here, the res object is offering the info about the request. We can then use console.log after the form is submitted.

Next, implement the component to App.js:

Axios React code screenshot 8

Time to test our code again. Start the server:

You should find a new form that takes the user’s name and removes it from the list:

Step 5: Apply Base Instance in Axios

Now, we will work with Axios base instance. Here, we can define a URL and other configuration elements. To implement it, create a separate file api.js:

Axios React code screenshot 9

Open it in a text editor and enter the following code:

Once it’s set, we can use it inside the PersonRemove component. Here’s what the code would look like:

Axios React code screenshot 10

Here, http://jsonplaceholder.typicode.com/ is set as the base URL. Now, we no longer need to use the full URL every time we reach an endpoint of the API.

Step 6: Implement async and await

In this section, we will have a look at how to implement async and await to work with promises. The await keyword resolves promise and returns value. We can assign this value to a variable for more comfortable usage.

Here’s what the updated code of PersonRemove.js would look like:

Here, we’ve replaced .then(). Once promise is resolved, we store the value in the variable response.

Final Thoughts

In this tutorial, we’ve explored various examples of using Axios to work with REST API. The codes showcase creating HTTP requests and handling responses.

Interested in learning more about JavaScript? Check out our other beginner guides on various JavaScript concepts and features, for example, date and time, string manipulation, classes, and objects.

Happy Computing!