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.

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.
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

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.

*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

  • 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

  • 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.

Axios POST Request

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

Syntax

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

  • 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).
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

  • This will update the data of name abc.
  • Now, letā€™s make a GET request to see the updates.

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ā€¦.!!!

Ā