# API handling: Axios!! or Fetch API!😱

### **Do you want to pull in weather data for your users?** 😎

### **Want to make a site that tracks COVID 19 cases?** 😎

You could do all of these by using API integration and giving your code superpowers to automate the whole process.

In JavaScript, Fetch API and Axios are widely used to implement HTTP requests. But, choosing one isn’t easy since they both have some unique features.

<aside>
💡 Before you go through this blog be familiar with React Hooks. In this blog, we will learn how to send HTTP requests (GET, POST, PUT, and DELETE requests) from React to a backend API using the Axios Library to manage API calls in React.

</aside>

## **Why Fetch Data?** 🤪

- When you are just starting developing web applications with **React** you probably won't need any external data at the beginning.
- However, at some point, you want to request real-world data from your own or a third-party API.
- For Example: if you want to build Weather Forecast Application, it is faster and more convenient to use free data sources available on the Internet but you need someone who takes care of retrieving data.

To fetch that data from the server, you’ll need an HTTP library.

### React has two methods for handling HTTP requests

- Axios
- Fetch API

While fetch API is in-built, Axios is an external library.

## **The Fetch API**

- **Fetch API** is built into most modern browsers on the window object (window.fetch) and enables us to make HTTP requests very easily.

```jsx
import {useEffect} from "react";

const fetchData = () => {
// Where we're fetching data from
return fetch("http://localhost:3000/getdata")
// We get the API response and receive data in JSON format
  .then((response) => response.json()) //processing data with JSON (An extra step)
  .then((data) => console.log(data))   
  .catch ((error) => console.error(error));}
```

- We will create a method called **fetchData().** It will call **fetch()** method with provided URL, then kept the result and process it (cleaning the unwanted data) by JSON data and print it to the console.
- Fetch is promise-based means we can also catch errors using the **.catch()** method. Any error encountered is used as a value to update our error’s state.
- Added to this we make this request within the **useEffect()** hook with an empty dependencies array as the second argument so that our request is only made once, not dependent on any other data.

```
import {useEffect} from "react";
useEffect(() => {
    fetchData()
  }, []);
```

So if we get the data from Fetch API then why to use Axios (an external Library) 🙄.

First of all, we will try to fetch API with Axios 

### What is Axios??

- Axios is a library that helps us make HTTP requests to external resources.
- It is a promise-based HTTP client library generally used with React.
- It automatically parses JSON for you.

## **Fetching Data with Axios library**

### *Axios GET Request*

```jsx
useEffect(()=>{
// GET Request using axios inside useEffect Hook
     const getRequestHandler = async () => {
            const getResponse = await axios.get("http://localhost:3000/getdata");
               setDetails(getResponse.data.main);
};
getRequestHandler();
},[]); // empty dependency array means this effect will only run once
```

- GET request from React using **Axios**, we use an **async** function and the **await** javascript expression to wait for the promises to return instead of using the promise **then()** method.
- Here to make a GET request we use the ***get Method*** and pass the URL as an argument.
- Then **getResponse** object has another object named **data** and this **data** contains the value returned by the API. Let in our case it is **main**, So the ***getResponse.data.main*** are saved in the state that we have created in the component.
- Now we have stored the required data in our state created and from there we can render it to different components.

<aside>
💡 **Why did you choose Axios instead of Fetch** 🧐

</aside>

*****JSON Data Transformation*****

- ***Axios*** perform an ****Automatic JSON data transformation**** while using ***fetch()***, however, you’d have to do it manually.
- Using the **fetch()** method, with the response, the user needs to process the **response.json()** action to ****stringify data.

***Error Handling***

**Fetch**

![Screenshot 2022-02-21 130510.png](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/3582736d-d528-4b30-9776-78e60f6f241b/Screenshot_2022-02-21_130510.png)

- In the case of Fetch, if we provide an incorrect URL it will not throw network errors automatically so we need to manually check.
- We need to check the response status irrespective of response type since a **Fetch()** promise is rejected only if the request is rejected somehow, else you need to verify the response type and then throw the error from then.
- Therefore, you must always check the **response.ok** property when you work with **fetch().**

**Axios**

![Screenshot 2022-02-21 134533.png](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/1899770d-6117-49eb-81f3-3e46fddf0fd3/Screenshot_2022-02-21_134533.png)

- In **Axios**, handling errors is pretty easy because **Axios** throws network errors. If there will be a bad response like 404, the promise will be rejected and will return an error. Therefore, you need to catch an error, and you can check what kind of error it was.

<aside>
💡 So, Axios provides a more comfortable to use API in comparison with fetch(). Axios is a clear winner to send HTTP requests based on its simplicity and ease of use.

</aside>

### *Axios POST Request*

- In a POST request, data is sent from the client-side to the server-side.

**Syntax**

```jsx
const postRequestHandler = async() => {
    const data = { name, age };
    const response = await axios.post( "http://localhost:3000/insertdata", data);
    }
  }
```

- To make a **POST request**, the **post** method is used and unlike the GET method, it has two arguments - URL and an object. The object contains the data that is to be sent to the server-side.
- Look at the Post component.

![Screenshot 2022-02-21 142730.png](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/20a74bcb-22b2-4007-9152-f187b839523f/Screenshot_2022-02-21_142730.png)

- In the above component, two input fields are provided to add the values for name and age. With the click of the button, the values added will be sent to the server-side using Axios.
- Now, let’s again make a GET request to verify if the data was inserted successfully or not.
- The inserted data is visible at the end.

### *Axios DELETE Request*

- DELETE Request is used to delete data.
- To delete a records, in this case the **name** is sent from the client-side to the server-side.
- And in the DELETE component we will triggered a onClick function such as **deleteRequestHandler(name).**

```jsx
const deleteRequestHandler = async (name) => {
  const response = await axios.delete(
    `http://localhost:3000/deletedata/${name}`
  );
};
```

- The API handler on the server-side is expecting a value for the **name**. So, we have passed it as params in the URL itself.
- Now, let’s make a GET request to verify if the record was deleted or not.

### *Axios PUT Request*

- The PUT method allows you to update an entire object.
- To do so, you'll once again create a button in the PUT component. But this time, the button will call a function that is **putRequest** to update a post:

![Screenshot 2022-02-21 150448.png](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/d259413c-9543-43ba-8190-0596018427d2/Screenshot_2022-02-21_150448.png)

- This will update the data of name abc.
- Now, let’s make a GET request to see the updates.

<aside>
📌 **SUMMARY:** Axios and fetch() are all great ways of consuming APIs but I advise you to make use of Axios when building applications. With this knowledge, you should undoubtedly and quickly connect to all kinds of APIs with React and use the Axios methods.

</aside>

<aside>
📌 **WHAT WE LEARN:** We have now seen what makes Axios better than the native Fetch API by performing Axios HTTP requests in React. We also looked at how Axios allows us to handle our errors better.                                                                                                         **Hopefully, you understood all we did in this blog and can now perform GET, PUT, POST, DELETE requests comfortably. Gracias!** 🤩

</aside>

If you have any questions, you can leave them in the comments section below and I will be happy to answer every single one.

**Thank you for reading this blog….!!!**
