The Complete Guide to Use Axios With React

How to Use Axios in React? A Complete Guide

Different frontend frameworks are popular in the global tech industry, and React is one of them. Developers use React to build web front-ends, and while being so popular, using it is not a walk in the park, even with different backend languages.

For instance, developers still need to connect the front end with a web API for data consumption. This is where innovations like Axios comes in. Axios is a lightweight HTTP client-based library package that is great at communicating with REST APIs. Companies like Modanisa and Hotjar rely on Axios in their techstacks.

Developers also use it to call backend API interfaces from React’s front end, which is impressive. This article explains what Axios is, its features, and its benefits to frontend developers and other users. So, if you’re wondering how to use Axios in React, this guide will provide all the tips and guidance you need. 

What is Axios?

Axios is an HTTP client for JavaScript, which is capable of making HTTP requests from a browser, while handling request and response data transformation simultaneously. It comes in handy when communicating with the backend.

This functional HTTP client supports Promise API native to JS ES6 and is a library that developers can use to make requests to an API, return data from APIs, and work with the data in React. Amongst HTTP clients, Axios is popular, with more than 70,000 stars on GitHub. 

Benefits of Axios

Axios encourages developers to communicate with APIs in their React applications easily. While this is achievable via other means such as AJAX or fetch, Axios goes further to offer more functionality that benefit React-reliant applications. 

In reality, you can use several other libraries in place of Axios, especially if you are unsure of your needs. So why should you use Axios? Below are some solid reasons we think Axios will serve you as a client to make HTTP requests.

  • You can use Axios on the server and client side. Besides, if you are writing a Node.js app, know that you can use Axios in a different environment other than the browser.
  • Axios is efficient because it does much with less code, and you only require a single .then() callback to access the JSON data you request, unlike options like the Fetch API where this isn’t possible.
  • The JavaScript HTTP client is great for its strong defaults in working with JSON data. Other close alternatives like Fetch API might need you to set your headers or complete tedious tasks such as converting request bodies to JSON strings. With Axios, you don’t have to go through the hassle.
  • Axios boasts of function names that match every HTTP method, and to carry out a GET request; users use the .get() method.
  • If you need better error handling, Axios will throw 400 and 500 range errors for users. This is unlike Fetch API, where you may have to throw the error yourself after checking the status code.

Do you have any questions about how to use Axios?

  Don’t hesitate to drop us a line and schedule a consultation. We can help you!

Get in touch

Prerequisites

If you want to start an Axios React Native project, there are some important software and resources you need to have. Below are some of them:

  1. First, you must install a Node.js v10.16.0 on your computer, whether on a macOS or Ubuntu 18.04.
  2. Next, you need to set up a new React using Create React App
  3. Finally, have at least a basic understanding of JavaScript, CSS, and HTML.

Note: Keep in mind this tutorial is executed with Node.js v16.13.1, npm v8.1.4, react v17.0.2, and axios v0.24.0.

#1. Install Node.js v10.16.0 On Your Computer

Node.js is a popular open-source JavaScript environment for building server-side apps. This runtime environment powers many client-side development tools for some of the more recent JavaScript frameworks. 

To install the Node.js v10.16.0 on your computer, you need a macOS device that runs on High Sierra or a greater release, has internet connectivity, and administrative access. After you’ve used the macOS terminal, install Xcode Command line tools, and installed and set up Homebrew. You can then proceed to search for and install Node.js. 

Here’s how to do it, starting with searching for packages related to Node.js: 

brew search nodejs

You will find a comprehensive list of packages that you can install on your computer, like the one below:

==> Formulae

node.js

nodejs

These two packages above can install Node.js on your computer, and they are available for users who are unsure whether they need node.js or nodejs. After deciding which to use, execute the command below to install the nodejs package.

brew install nodejs

After executing the previous command, you should see an output similar to your Terminal. While Homebrew will proceed to install several dependencies, it downloads Node.js by itself. 

==> Installing dependencies for node: icu4c

==> Installing node dependency: icu4c

==> Installing node

==> Downloading https://homebrew.bintray.com/bottles/node-11.0.0.sierra.bottle.tar.gz

######################################################################## 100.0%

==> Pouring node-11.0.0.sierra.bottle.tar.gz

==> Summary

🍺  /usr/local/Cellar/node/11.0.0: 3,936 files, 50.1MB

Homebrew will also install several other related tools such as npm to make installing and updating Node.js packages and libraries easier. If you need to see the version of the Node.js you just installed, type the following: 

node -v

The above command will give an output of the version of Node.js that you’ve installed. This version should be the most current stable version available.

v11.0.0

You can check the version of npm using this:

npm -v

You will see the displayed version as:

6.4.1

You can then use npm to install more frameworks, libraries, and components. If you want to update your Node.js, you will have to update Homebrew to get the most current list of packages before upgrading Node.js:

brew update

brew upgrade nodejs

#2. Creating a New Project with Create React App

You need to create a new project with the Create React App, and the npm package manager can help. It will run a unique remote script that will copy the relevant files into a new directory. After copying the file, the script will install all the dependencies.

After installing Node, you need a package managing app—npm.npm. This is one additional app that will install JavaScript package in projects you work on. This package managing application will also keep track of details of your project.

Besides, npm has another tool—npx—that runs executable packages. So you can run the Create React App code without downloading the project. Keep in mind that the executable package will run the create-react-app installation into the directory of your choice.

It will also proceed by first creating another project in a directory. In this tutorial, we call this new project your-axios-tutorial. Remember that the said directory doesn’t necessarily have to be in existence beforehand; our executable package will create this directory for us.

Meanwhile, the script will run npm install within the directory of our project, which should subsequently download any extra relevant dependencies. So to install your base project in this Axios React Native tutorial, you have to run the command below:

npx create-react-app your-axios-tutorial

The command above should begin a build process that will download a base code and several dependencies. As the script ends, you should see a success message saying this:

Success! Created your-axios-tutorial at your_file_path/your-axios-tutorial

Inside that directory, you can run several commands:

  npm start

    Starts the development server.

  npm run build

    Bundles the app into static files for production.

  npm test

    Starts the test runner.

  npm run eject

    Removes this tool and copies build dependencies, configuration files

    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd your-axios-tutorial

  npm start

Happy hacking!

After that, your_file_path becomes your current path, but it should be /Users/your_username for macOS users. Users on Ubuntu servers will see something like /home/your_username.

If you explore some more, you will find a list of npm commands that allows users to build, run, test, and start their app. However, your new project is set up in a new directory, but you can change it into this new directory:

cd your-axios-tutorial

Now, you are inside your project’s root and have created a new project while adding all the relevant dependencies. The next stage in our how-to use Axios in React guide is to add Axios to our project until we can use the async and await, so keep reading.

Do you need help to get started with your Axios Project?

  At Innuy, we have a talented team available to help you. Schedule an intro call!

Get in touch

Step 1: Add Axios to Your Project

Adding Axios to your project is the first step of using Axios with React, and the step from the second prerequisite will come in handy.

npx create-react-app react-axios-example

Opening your terminal and changing directories into your project should add Axios to the projects:

cd react-axios-example

Next up, you need to run this command npm install axios@0.24.0 to install Axios, then import Axios into the specific file in which you will be using it.

Step 2: Make a GET Request

The next step in our React Axios project tutorial is to create a component and import Axios into it. Doing this will enable you send GET request. Within your React Project, you must create a new component—PersonList.

To pull this off, create a components subdirectory in your src directory like this:

mkdir src/components

Next, in this new directory, you will need to create PersonList.js and add this code to the component: 

import React from ‘react’;

import axios from ‘axios’;

export default class PersonList extends React.Component {

  state = {

    persons: []

  }

  componentDidMount() {

    axios.get(`https://jsonplaceholder.typicode.com/users`)

      .then(res => {

        const persons = res.data;

        this.setState({ persons });

      })

  }

  render() {

    return (

      <ul>

        {

          this.state.persons

            .map(person =>

              <li key={person.id}>{person.name}</li>

            )

        }

      </ul>

    )

  }

}

In this stage, you must first import React and Axios to use the two in the component, then proceed to hook into the componentDidMount lifecycle hook and complete a GET request.

Next up, use axios.get(url) with the URL from a select API endpoint to receive a promise which should return a response object. Within the response object, you will find data that will then be assigned person as its value. 

If you need to, you can also retrieve other information about your request, including information inside res.request or the status code via res.status. After that, you can then add the component below to your app.js:

import PersonList from ‘./components/PersonList.js’;

function App() {

  return (

    <div ClassName=”App”>

      <PersonList/>

    </div>

  )

}

Once that is done, you can proceed to run your app with this command:

npm start

Note: If you view the application in the browser, you will find a list of 10 names.

Step 3: Make a POST Request

This next step in our React Axios example involves using Axios with another HTTP request method, POST. Within your React project, you must create another component—PersonAdd. 

Next, create PersonAdd.js and proceed to add the code below to create a unique form that permits user input and POSTS the content to an API:

import React from ‘react’;

import axios from ‘axios’;

export default class PersonAdd extends React.Component {

  state = {

    name: ”

  }

  handleChange = event => {

    this.setState({ name: event.target.value });

  }

  handleSubmit = event => {

    event.preventDefault();

    const user = {

      name: this.state.name

    };

    axios.post(`https://jsonplaceholder.typicode.com/users`, { user })

      .then(res => {

        console.log(res);

        console.log(res.data);

      })

  }

  render() {

    return (

      <div>

        <form onSubmit={this.handleSubmit}>

          <label>

            Person Name:

            <input type=”text” name=”name” onChange={this.handleChange} />

          </label>

          <button type=”submit”>Add</button>

        </form>

      </div>

    )

  }

}

In the handleSubmit function, you can stop the default action of the form and then update the state to user input. However, when you use POST, you get a similar response object to the information that you can utilize within a then call.

But to finish the POST request, you need to capture the user input and proceed to add the input with the POST request, which should get you a response. Moreover, you can apply the console.log command to the response to show the user input in the form. Add the component below to your app.js:

import PersonList from ‘./components/PersonList’;

import PersonAdd from ‘./components/PersonAdd’;

function App() {

  return (

    <div ClassName=”App”>

      <PersonAdd/>

      <PersonList/>

    </div>

  )

}

Once that is done, you can proceed to run your app with this command:

npm start

Note: You can look at the application in the browser. Also, you will get a form for submitting new users, and you can check the console right after submitting a new user.

Step 4: Make a DELETE Request

Here, we use axios.delete to properly delete items from an API and see how to pass a URL as a parameter. In your React project, you must make a new component—PersonRemove. Then create PersonRemove.js before adding the code below to delete a user successfully:

import React from ‘react’;

import axios from ‘axios’;

export default class PersonRemove extends React.Component {

  state = {

    id: ”

  }

  handleChange = event => {

    this.setState({ id: event.target.value });

  }

  handleSubmit = event => {

    event.preventDefault();

    axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.id}`)

      .then(res => {

        console.log(res);

        console.log(res.data);

      })

  }

  render() {

    return (

      <div>

        <form onSubmit={this.handleSubmit}>

          <label>

            Person ID:

            <input type=”number” name=”id” onChange={this.handleChange} />

          </label>

          <button type=”submit”>Delete</button>

        </form>

      </div>

    )

  }

}

Know that the res object offers you the information about a request, and you can easily console.log the specific information again after you’ve submitted the form. Next, you can attach this component below to your app.js:

import PersonList from ‘./components/PersonList’;

import PersonAdd from ‘./components/PersonAdd’;

import PersonRemove from ‘./components/PersonRemove’;

function App() {

  return (

    <div ClassName=”App”>

      <PersonAdd/>

      <PersonList/>

      <PersonRemove/>

    </div>

  )

}

Once that is done, you can proceed to run your app with this command:

npm start

Note: You may view the app in the browser. What’s more, you will get a form for eliminating users. 

Step 5: Using a Base Instance in Axios

This next step in our React Axios example helps you set up a base instance. The base instance is necessary for defining a URL and other configuration elements. First, you need to create a different file named api.js:

nano src/api.js

Next, use the defaults below to export a new axios:

import axios from ‘axios’;

export default axios.create({

  baseURL: `http://jsonplaceholder.typicode.com/`

});

Once you’ve set up the default stance, you can use it within the PersonRemove component conveniently, and now you can proceed to import a new instance like the one below:

import React from ‘react’;

import API from ‘../api’;

export default class PersonRemove extends React.Component {

  // …

  handleSubmit = event => {

    event.preventDefault();

    API.delete(`users/${this.state.id}`)

      .then(res => {

        console.log(res);

        console.log(res.data);

      })

  }

  // …

}

Keep in mind that http://jsonholder.typicode.com/ is now the base URL. You don’t necessarily have to type the complete URL every time you aim for a different endpoint on the API.

Step 6: The Use of async and await

This step focuses on how to leverage async and await to exploit promises. In this stage, our await keyword helps resolve promise and return value. Subsequently, we can then assign the value to a specific variable.

import React from ‘react’;

import API from ‘../api’;

export default class PersonRemove extends React.Component {

  // …

  handleSubmit = event => {

    event.preventDefault();

    const response = await API.delete(`users/${this.state.id}`);

    console.log(response);

    console.log(response.data);

  }

  // …

}

From our code sample, you will discover that we end up replacing the .the(). Moreover, we’ve managed to resolve the promise while storing the value within the response variable. 

Need help with your Axios project?

   At Innuy we have many years of experience in the field. Our talented developers can help you if you book a consultation!

Get in touch

How to Deal With Errors in Axios

Sometimes when making a request, you might encounter an error that can be frustrating. Users may have a network error, pass along incorrect data, or even make a request to the wrong endpoint. So how do you deal with errors in Axios? 

We’ll simulate an error by sending a request to the endpoint of a non-existent API (/posts/asdf), and this request should return a 404 status code:

import axios from “axios”;

import React from “react”;

const baseURL = “https://jsonplaceholder.typicode.com/posts”;

export default function App() {

  const [post, setPost] = React.useState(null);

  const [error, setError] = React.useState(null);

  React.useEffect(() => {

    // invalid url will trigger an 404 error

    axios.get(`${baseURL}/asdf`).then((response) => {

      setPost(response.data);

    }).catch(error => {

      setError(error);

    });

  }, []);

  if (error) return `Error: ${error.message}`;

  if (!post) return “No post!”

  return (

    <div>

      <h1>{post.title}</h1>

      <p>{post.body}</p>

    </div>

  );

}

So rather than executing the .then() callback, Axios throws an error and runs the .catch() callback function. With this function, we put the error data in a state to alert the project’s users about the error.

In other words, if we have an error, we will display an error message for users to see. So running this code will pull up this text: “Error: Request failed with status code 404″#

Conclusion

You can rely on Axios to attend to conversion request and response data cancellation request, make an XMLHttpRequest through the browser, or promise API Intercept request. 

Besides, if you need an automatic conversion of JSON data or client support to stop CSRF/XSRF, Axios is your best pick. An Axios React Native project will help developers easily communicate with APIs in their React app and more when paired with React.

Leave a Reply

Your email address will not be published. Required fields are marked *