How to use Axios with React
Tags: react, beginners, programming, tutorial
Published: 2022-08-19 09:36:07

## Introduction

[Axios](https://axios-http.com/docs/intro) is a promise-based HTTP Client for node.js and the browser. Thus, it works equally well in front-end JavaScript applications and back-end Node servers.

This article shows how to use Axios in a simple [React](https://reactjs.org/) application. React is a JavaScript library for building user interfaces, so we'll use Axios here for browser-based user interfaces.


## Prerequisites



<p>To follow along, you’ll need the following:</p>
<ul>
<li>
<a href="https://nodejs.org/en/"  target="_blank" rel="noreferrer"  >
Node.js </a> version 16.16.0 installed on your computer.

</li>

<li>
A new React project set up with
<a href="https://reactjs.org/docs/create-a-new-react-app.html" >Create React App</a>
</li>

<li>IDE or text editor of your choice, such as <a href="https://www.sublimetext.com/" target="_blank" rel="noreferrer noopener"  >Sublime Text</a> or <a href="https://code.visualstudio.com/" target="_blank" rel="noreferrer noopener">Visual Studio Code</a></li>

</ul>


We will cover:

<ul>

<!-- <li> 
<a href="#Prerequisites for this tutorial using Axios with React" >
Prerequisites for this tutorial using Axios with React

</a>

</li> -->

<li>

<a href="#Setting up our React project" >
Setting up our React project

</a>
</li>

<li>

<a href="#Adding Axios to our React app" >
Installing Axios into our React application
</a>
</li>

<!-- <li >
<a  href="#Using Axios with a simple import in your React component" >Using Axios with a simple import in your React component</a>

</li> -->

<li> <a href="#Sending CRUD API requests with Axios" >Sending CRUD API requests with Axios</a>
    <ul>
      <!-- <li> <a href="#{JSON} Placeholder" > {JSON} Placeholder</a>  </li> -->
      <li> <a href="#Making a get request" > How to make a GET request</a>   </li>
      <li><a href="#Making a post request" >How to make a POST request</a> </li>
      <li> <a href="#Making a put request" > How to make a PUT request</a></li>
  <li> <a href="#Making a delete request" > How to make a DELETE request</a></li>
     <li> <a href="#Handling errors" > Handling errors</a></li>
      <li>  <a href="#Base Instance" > Base Instance</a></li>
     <li>  <a href="#async and await" >How to use async and await</a></li>
    </ul>
  </li>
</ul>

<!-- <h2 id="Prerequisites for this tutorial using Axios with React">Prerequisites for this tutorial using Axios with React</h2> -->


<h2 id="Setting up our React project">Setting up our React project</h2>

<p>We will create our project following the step mentioned in step one above. Let's get started by running the following command:</p>

<pre>
npx create-react-app react-axios-tutorial
</pre>

<p>We will now navigate to the project directory by running:</p>

<pre>
cd react-axios-tutorial
</pre>

<p>

I have chosen to name the project react-Axios-tutorial
because we are learning how Axios works in React.

</p>

<p>
Currently, this is how my project structure looks.
</p>

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fa9957x3o6jrez2xc864.png)


<h2 id="Adding Axios to our React app"  >Installing Axios into our React application</h2>

To install Axios, we run the following command:

<pre>
npm i axios
</pre>


<p>

It is important to verify the dependencies in the <code>package.json</code> file to confirm whether Axios has been installed.  

</p>

<p>
 This is the current state of my dependencies.

</p>

```javascript

//...

  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.27.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },

  //...


```






<!-- <h2 id="Using Axios with a simple import in your React component" >Using Axios with a simple import in your React component</h2> -->

<h2 id="Sending CRUD API requests with Axios"  >Sending CRUD API requests with Axios</h2>

<p>In this section, we will discuss how we can send CRUD requests.
We will create, retrieve, update and delete data using a publically available <a href="https://jsonplaceholder.typicode.com/"  >JSONPlaceholder</a> </p>

<!-- <h3 id="{JSON} Placeholder" >JSONPlaceholder: Free fake API for testing and prototyping.</h3> -->
<!-- <P>JSONPlaceholder is a free online REST API that we can use whenever you need some fake data.
</P> -->

<h3  id="Making a get request" > How to make a GET request</h3>

<p>
The first step is to create a component folder in our src directory to make a <code>GET</code> request. We navigate into the src directory and then run the code below:

</p>

<pre>
mkdir Components
</pre>

<p>
In this directory, we create a <code> Users.js</code> file and add the code below:
</p>

```javascript
import React, { useEffect, useState } from "react";
import axios from "axios";

function Users() {
  const [post, setPost] = useState([]);

  useEffect(() => {
    axios.get("https://jsonplaceholder.typicode.com/users").then((data) => {
      console.log(data);
      setPost(data?.data);
    });
  }, []);

  return (
    <div>
      Users
      {post.map((item, i) => {
        return (
          <div key={i}>
            <p>{item?.name}</p>
          </div>
        );
      })}
    </div>
  );
}

export default Users;
```

<p>
The first thing we do is import <code>React</code>, <code>useEffect</code> , and <code>useState</code> hooks. We also import Axios so we can make HTTP requests.
In the <code>useEffect</code> hooks, we use the <code>GET</code> method to make a<code>GET</code> request to our endpoint,  then use the  <code>then()</code>method to get back all of the response data we use to update our user's state.
</p>

<p>
We received an object as a response. A data array with properties address, company, email, id, name, phone, username, and website is accessed. The properties are then assigned to the user's state and made available in the component.
</p>


> There are also other details about the request, like the status code under `res.status` or more details inside `res.request`.

<!-- <small>There are also other details about the request, like the status code under `res.status` or more details inside `res.request`.</small> -->

<p>
Next, we add our <code>Users</code> component to our <code>app.js</code> file
</p>

```javascript
import Users from "./Components/Users";

function App() {
  return (
    <div>
      <Users />
    </div>
  );
}

export default App;
```

<p>The next step is to start our application with:</p>

<pre>npm start</pre>

<p>We should have something that looks like the image below.</p>

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qhjcqutplm5zgu5w76m4.png)

<h3 id="Making a post request" > How to make a POST request</h3>

<p>
Using Axios with POST is the next step.
We will need to create a new component named <code>AddUser.js</code> inside our Component directory.
</p>

<pre>
touch AddUser.js
</pre>

<p>
The following code is added to <code>AddUser.js</code> to create a form that allows user input and then sends the content to an API:
</p>

```javascript
import React, { useState } from "react";
import axios from "axios";

function AddUser() {
  const [name, setName] = useState({
    name: " ",
  });

  const handleChange = (e) => {
    e.preventDefault();

    setName({
      name: e.target.value,
    });
  };

  const submitForm = (e) => {
    e.preventDefault();

    axios
      .post(`https://jsonplaceholder.typicode.com/users`, { name })
      .then((res) => {
        console.log(res);
        console.log(res.data);
      });
  };

  return (
    <div>
      <p>Add Users</p>
      <div>
        <form onSubmit={submitForm}>
          <label>
            User Name:
            <input type="text" name="name" onChange={handleChange} />
          </label>
          <button type="submit">Add</button>
        </form>
      </div>
    </div>
  );
}

export default AddUser;
```

<p>
Using the <code>SubmitForm</code> function, we stop the form's default action. After that, we update the <code>state</code> to reflect the <code>user</code> input.
The <code>POST</code> method gives us the same response object with information we can use inside the <code>then()</code> method.
</p>

<p>
It is necessary to capture the <code>user</code> input before we can complete the <code>POST</code> request. Next, we add the input along with the <code>POST</code> request, which will return a response. After that, we can <code>console.log</code> the response, which displays the <code>user</code> input.
</p>

<p>Now, we add the component to our <code>app.js</code> </p>

```javascript
import AddUser from "./Components/AddUser";
import Users from "./Components/Users";

function App() {
  return (
    <div>
      <Users />
      <AddUser />
    </div>
  );
}

export default App;
```

<!-- <p>The next step is to start our application with:</p>

<pre>npm start   </pre>

<p>Now, we can view the application in the browser. The form for submitting new users will appear. Once we've added a new user, we'll need to check the console to see that the user has appeared.</p> -->

<h3  id="Making a put request" > How to make a put request</h3>

<p>
Using Axios with <code>PUT</code> method is the next step.

We will need to create a new component named <code>UpdateUser</code> inside our Component directory.

<pre>
touch UpdateUser.js
</pre>

</p>

<p>
The following code is added to <code>UpdateUser</code> to create a form that allows user input and then update the content to an API:
</p>

```javascript
import React, { useEffect, useState } from "react";
import axios from "axios";

function UpdateUser() {
  const [state, setState] = useState({
    Name: "",
    userName: "",
  });

  const handleChange = (evt) => {
    const value = evt.target.value;

    setState({
      ...state,
      [evt.target.name]: value,
    });
  };

  const submitForm = (e) => {
    e.preventDefault();
    console.log(e);
    console.log(state);

    axios
      .put(`https://jsonplaceholder.typicode.com/users/1`, { state })
      .then((res) => {
        console.log(res);
        console.log(res.data);
      });
  };

  return (
    <div>
      <p>Add Users</p>
      <div>
        <form onSubmit={submitForm}>
          <label>
            User Name:
            <input
              type="text"
              name="Name"
              placeholder="name"
              value={state.Name}
              onChange={handleChange}
            />
            <input
              type="text"
              name="userName"
              placeholder="username"
              value={state.userName}
              onChange={handleChange}
            />
          </label>
          <button type="submit">Add</button>
        </form>
      </div>
    </div>
  );
}

export default UpdateUser;
```

<p>
In the code above, we use the <code>PUT</code> method from Axios. As with the <code>POST</code>method, we include the properties we wish to add to the updated resource.
</p>

<p>
Again, using the <code>then()</code> method, the data is updated in JSX.
</p>

<p>
Next, we add our <code>UpdateUser</code> component to our <code>App.js</code> file
</p>

```javascript
import AddUser from "./Components/AddUser";
import UpdateUser from "./Components/UpdateUser";
import Users from "./Components/Users";

function App() {
  return (
    <div>
      <Users />
      <AddUser />
      <UpdateUser />
    </div>
  );
}

export default App;
```

<!-- <p>The next step is to start our application with:</p>

<pre>npm start</pre>

<p>We can now view the application in the browser. A form will appear for adding new users. Also, we can check the console after submitting a new user.</p> -->

<h3  id="Making a delete request" > How to make a delete request</h3>

<p>
By using the <code>Delete</code> method and passing a URL as a parameter, we will see how to delete items from an <code>API</code>.

We need to create a new component called <code>RemoveUser.js</code>  within our React project.

</p>

<p>To delete a user, we create <code>RemoveUser.js</code> and add the following code:</p>

```javascript
import React, { useState } from "react";
import axios from "axios";

function RemoveUser() {
  const [state, setState] = useState(" ");

  const handleChange = (e) => {
    setState({ id: e.target.value });
  };

  const handleRemove = (evt) => {
    evt.preventDefault();

    axios
      .delete(`https://jsonplaceholder.typicode.com/users/${state.id}`)
      .then((response) => {
        console.log(response);
        console.log(response.data);
      });
  };

  return (
    <div>
      Remove User
      <div>
        <form onSubmit={handleRemove}>
          <label>
            User ID:
            <input type="number" name="id" onChange={handleChange} />
          </label>
          <button type="submit">Delete</button>
        </form>
      </div>
    </div>
  );
}

export default RemoveUser;
```

<p>Again, the <code>response</code> object contains information about the request. After the form is submitted, we can 
<code>console.log </code> that information again.

</p>

<p>Our <code>app.js</code> file should include this component:</p>

```javascript
import AddUser from "./Components/AddUser";
import RemoveUser from "./Components/RemoveUser";
import UpdateUser from "./Components/UpdateUser";
import Users from "./Components/Users";

function App() {
  return (
    <div>
      <Users />
      <AddUser />
      <UpdateUser />
      <RemoveUser />
    </div>
  );
}

export default App;
```

<!-- <p>Then, we run our application</p>

```
npm run start

``` -->

<h3  id="Handling errors" > Handling errors</h3>

<p>
Is Axios capable of handling errors?
</p>

<p>When making a request, what happens if there is an error? </p>

<p>There may be a problem passing along data, It may be that a wrong endpoint is requested, or there may be a network issue.
To simulate an error, we'll send a request to an <code>API</code> endpoint that doesn't exist: <code>/users/obmm</code>.
</p>

<p>This request will return a <code>404 status code</code>:</p>

<!-- <p>This request will return a <code>404 status</code></p> -->

<p>To handle an error, we create <code>Errorhandling.js</code> and add the following code:</p>

```javascript

import axios from "axios";
import React, { useEffect, useState } from "react";

function Errorhandling() {
  const [users, setUsers] = useState([]);
  const [error, setError] = React.useState(null);

  useEffect(() => {
    axios
      .get(`https://jsonplaceholder.typicode.com/posts/obmm`)
      .then((response) => {
        setUsers(response.data);
      })
      .catch((error) => {
        setError(error);
      });
  }, []);

  if (error) return `Error: ${error?.message}`;
  if (!users) return "No user!";

  return (
    <div>
      Errorhandling
      <div>
        Users
        {users.map((item, i) => {
          return (
            <div key={i}>
              <p>{item?.name}</p>
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default Errorhandling;
```

<p>

As a result, Axios will throw an error instead of executing the <code>then()</code> method.

</p>

<p>
We are using this function to alert our users about the error by taking the error data and putting it in a state. Thus, if an error occurs, an error message will appear.
</p>

<p>
A user is alerted about the error by putting the error data in the state. A message is displayed if there is an error.
Upon running this code, we'll see: "Error: Request failed with status code 404".
</p>

<p>Our <code>app.js</code> file should include this component:</p>

```javascript

import AddUser from "./Components/AddUser";
import Errorhandling from "./Components/Errorhandling";
import RemoveUser from "./Components/RemoveUser";
import UpdateUser from "./Components/UpdateUser";
import Users from "./Components/Users";

function App() {
  return (
    <div>
      <Users />
      <AddUser />
      <UpdateUser />
      <RemoveUser />
      <Errorhandling />
    </div>
  );
}

export default App;

```

<!-- <p>The next step is to start our application with:</p>

<pre>npm start</pre> -->





<h3  id="Base Instance" > Base Instance</h3>


<p>We'll set up a base instance with a URL and other configuration elements in this section.
</p>

<p>The first step is to create a separate file named <code>api.js</code>:</p>


<p>Let us add this code to our  <code>api.js</code></p>


```javascript 
import axios from 'axios';


export default axios.create({
  baseURL: `http://jsonplaceholder.typicode.com/`
});


```


<p>We will be using the <code>API</code> file in our <code>RemoveUser.js</code>  component.</p>

<p> We import the new instance like this:</p>


```javascript

import React, { useState } from 'react'
import axios from 'axios';
import API from './API.js';

function RemoveUser() {

  // ...

 const handleRemove = (evt)=>{
    evt.preventDefault();

       API.delete(`users/${state.id}`)
      .then(response => {
        console.log(response);
        console.log(response.data);
      })
}

  // ...

}

export default RemoveUser

```
<p>It is no longer necessary to type out the whole URL each time we want to access a different <code>API</code> endpoint since <code>http://jsonplaceholder.typicode.com/</code>  is now the base URL.</p>



<h3 id="async and await"  >The use of async and await</h3>


<p>This section shows how we can work with <code>promises</code>  using <code>async</code> and <code>await</code> .</p>

<p>Promises are resolved using the <code>await</code> keyword, which returns their <code>value</code>. Afterwards, the <code>value</code> can be assigned to a variable.</p>


```javascript

import React, { useState } from 'react'
import axios from 'axios';
import API from './API.js';

function RemoveUser() {

  // ...

 const handleRemove = (evt)=>{
    evt.preventDefault();

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

  // ...


}

export default RemoveUser

```


<p>
In the example above, the <code>then</code> method is replaced. As a result, the <code>promise</code> has been fulfilled, resulting in the <code>value</code> being stored in the <code>response</code> variable.

</p>


## Conclusion


<p>

This tutorial demonstrated how Axios could be used inside a React application to create HTTP requests and handle responses.
</p>



<p>


Thanks for Reading 🌟🎉

</p>
<p>
It's great to see that you have enjoyed the article. Please, let me know what you think in the comment section.

</p>

<p>I'd love to connect with you at <a href="https://twitter.com/akinyemi_t">Twitter</a> </p>

</p>
On to another blog, some other day, till then Femi👋.
</p>