DEV Community

The ERIN
The ERIN

Posted on • Updated on

A Beginner's Guide to Using Fetch and Axios to Consume REST APIs in React

Without us being aware of it, we use APIs every day. Whenever we use our gadgets to check the weather, send our loved ones a social media message, or even shop online at our favorite store, we use an API. APIs are a vital component of our digital world and are an integral part of the software development process.
React is an open-source front-end JavaScript library that is popularly used to help developers build user interfaces and interactive elements on websites. Any front-end developer who wants to use React to create modern, reliable online applications must understand how to consume an API to fetch data for their React applications.

This article will serve as a guide to describe in simple and plain terms how to use the two most commonly used techniques, the Fetch API and Axios (a promise-based HTTP Client for Node.js and its browser), to consume RESTful APIs in your React app.
By the end of this article, you will understand more about how to use data from REST APIs to power your React Apps and the significance of APIs in general.

Prerequisite

  • Basic knowledge of JavaScript
  • Basic knowledge of ES6 JavaScript
  • Basic understanding of React and React Hooks.

An API is a link or intermediary that enables communication between two web servers or systems. An Application Programming Interface is referred to as an API.

Data communication between different software systems is made possible by this software middleman. Consider the following scenario from the real world: You walk up to the woman working the counter at your favorite pizza shop to place an order. You give her all the information she needs to know, including the type and amount of pizza you want. Your order is taken by her, and she sends it to the kitchen. Your pizza is done after 20 minutes, and you are pleased. When you paid at the counter, you were unaware of what was taking place in the background. This entire production process provides a detailed illustration of how an API functions. The messenger, or "API" in this case, was the woman behind the counter. She accepts your order and directs the chef to fulfill it. They give her the pizza, or in this case, the "data," when the kitchen is finished, so she may deliver it to you. She served as a vital communication channel between you and the kitchen. This is a clear explanation of what API is.
The "kitchen" and the interior workings of the other systems are off-limits. Only the API layer, also known as an End Point, is accessible to us.

An API endpoint is a digital location or a uniform resource locator (URL) where a request for data is sent by a software system to retrieve the digital resources that exist in that digital location.

Software programs can have multiple API endpoints that store different digital resources. Your weather app, for instance, might contain an endpoint for the weather in a city other than your own.

What is a REST API?

The REST API often called the RESTful API, is a software architecture style that uses the HTTP protocol to interact and communicate with a web server. It's commonly used because of its adaptability and reduced bandwidth utilization. Commonly, REST APIs communicate via HTTP requests to perform standard database functions like creating, reading, updating, and deleting records (also known as CRUD) within a resource. For example, a REST API would use a GET request to retrieve a record, a POST request to create one, a PUT request to update a record, and a DELETE request to delete one. A representation of the resource's state is communicated to the requester or client when an HTTP request is made. This information is delivered in any format, including JavaScript Object Notation, HTML, XLT, Python, PHP, or plain text. JSON is the most popular file format because of its readability by both humans and machines. The REST architecture helps increase developers’ productivity by allowing them to display the information on the client-side and store or manipulate the data on the server-side.

Example of a REST API

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi",
    "body": "quia et sumolestiae ut ut quas totam"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit "
  },
]
Enter fullscreen mode Exit fullscreen mode

How to consume REST API in React

In this article, I'll describe in plain English how to use the two most popular approaches—Fetch API and Axios(a promise-based HTTP Client for Node.js and its browser)—to consume REST APIs in your React projects.

We'll be using a functional component, which gives us the freedom to use React Hooks. The useEffect() hook and the useState() hook are the two that we'll require.

useEffect() Hook : We can perform HTTP requests inside function components using the useEffect hook. By including a variable in the second argument, we can instruct the useEffect to execute only when a specific state is reached or altered rather than the normal behavior of running after each render.

useState() Hook : We must prepare a state that enables us to retain the data when it is returned when we request data from a resource. This feature is made available to us via the useState hook.

Consuming APIs using the Fetch API

The Fetch API in JavaScript is a promise-based interface that allows you to fetch resources by making HTTP requests (i.e., either a GET request or a POST request) to servers from web browsers. It represents the eventual success or failure of an asynchronous operation using the JavaScript Promise. Either way, it can be rejected.

Basic Fetch Request Syntax

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));
Enter fullscreen mode Exit fullscreen mode

The fetch() method accepts two parameters: the URL of the resource you want to fetch and the init parameter, which is optional. It returns a promise that resolves into a response object, which contains the data that needs to be converted into a JSON format in order to work with it. In order to handle the response, the response object provides a number of helpful properties and methods, such as the then() and catch() methods.

Using Fetch() method in React Projects

In this section, we will be building a simple React app that allows us to consume an Advice Slip API, an external API that generates random advice slips.

For this example, we’ll use the Fetch API to retrieve the data from the resource. It is important to note the slight difference between using the fetch() method in Vanilla JavaScript and in React projects. The syntax is the same, but most fetch requests in a React application are executed inside a React component.

The first thing, we need to do is generate a new React project, by using the create-react-app. After initializing, make a new file called FetchAdvice.jsx in your src folder. All HTTP requests to fetch all of the data from a resource will be handled in this file

Image description

The useState() hook was used in the preceding code to declare a state variable that will store the data retrieved from the Advice API. Because the data we'll be expecting from the Advice API is a string containing random advice, we set the default value to an empty string. In some cases, the data retrieved from a resource may be of the array type. You'll need to set your initial value to an empty array for this.

As you may recall, the useEffect hook allows us to perform HTTP requests within function components. In the code above, we used the fetch() method within our useEffect hook to retrieve data from the Advice API immediately after our app loaded and after each render.

We don't need to add a method to the options array when using the fetch method to make GET requests because the default method is a "GET," but we do need to add a method to the options array for other requests, such as POST or DELETE.

Image description

To access and store each random advice in our state variable, we must destructure the data property in our response object, which gives us access to each random advice. The string can then be saved in our state variable.

To finish our work, we must handle promise rejection, which we can do with the catch() method.

Image description

Finally, we can display our fetched data in our JSX by adding our "advice" variable to an HTML element.

Image description

Consuming APIs using the Axios Method

Axios is a promise-based HTTP library that allows developers to send asynchronous HTTP requests to REST endpoints such as GET, POST, PUT/PATCH, and DELETE. It is isomorphic because it can run in both the browser and Node.js with the same codebase. It enables us developers to make data requests to either our own or an external server. Axios can be used with standard JavaScript as well as React or Vue.

How to Install Axios to your React Projects

Unlike the Fetch API, we must install the Axios library in order to use Axios in our React project. There are several installation options available; select the one that best suits your computer.

using npm:

$ npm install axios
Enter fullscreen mode Exit fullscreen mode

using bower:

$ bower install axios
Enter fullscreen mode Exit fullscreen mode

using yarn:

$ yarn add axios
Enter fullscreen mode Exit fullscreen mode

How to use Axios to perform GET Requests

After successfully installing Axios in your React project, add another file called FetchUsers to your src folder. In this file, we'll use a different type of API called the JSON Placeholder, which is a free API for testing.

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


const FetchUsers = () => {
   const [users, setUsers] = useState([]);

   useEffect(() => {
    axios
         .get('https://jsonplaceholder.typicode.com/users')
         .then((response) => response.json())
         .then((data) => {
            console.log(data);
            setUsers(data);
         })
         .catch((err) => {
            console.log(err.message);
         });
   }, []);

return (
   // ... display data here
);
};

Enter fullscreen mode Exit fullscreen mode

Because Axios is not a built-in JavaScript method, we must first import it into the FetchUsers file. To make a GET request, we must use the .get() method, which accepts the API endpoint, and then handle the response object with the .then() and .catch() methods.

Finally, we must loop through the "post" array in order to display the data in our application.

const FetchUsers = () => {
// ...

   return (
   <div className="user__container">
      {users.map((user) => {
         return (
            <div className="user__parent" key={user.id}>
                <h2 className="user__parent--name">{user.name}</h2>
                <p className="user__parent--username">{user.username}</p>
                <p className="user__parent--email">{user.email}</p>
            </div>
         );
      })}
   </div>
   );
};

export default FetchUsers;
Enter fullscreen mode Exit fullscreen mode

How to use Axios to make POST Request

We can use the HTTP POST request to send data to a server in order to create or update a resource. The data sent to the server is stored in the HTTP request body. According to the API guide, we can only send data to the JSON Placeholder API via the /post endpoint.
Create a new file called CreatePost in your src folder, where we will write our code to create a new post.

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


const  CreatePost = () => {
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');

  function newPost() {
    axios
      .post("https://jsonplaceholder.typicode.com/posts", {
        title: "Hello World!",
        body: "This is a new post."
      })
       .then((response) => response.json())
       .then((data) => {
         setPosts((posts) => [data, ...posts]);
         setTitle('');
         setBody('');
      })
      .catch((err) => {
         console.log(err.message);
      });
  }

const handleSubmitPost = (e) => {
   e.preventDefault();
   newPost(title, body);
};  

  return (
   <>
      <div className="newPost__container">
         <form onSubmit={handleSubmitPost}>
            <input type="text" className="post__input" value={title}
               onChange={(e) => setTitle(e.target.value)}
            />
            <textarea className="post__input"  
               value={body} onChange={(e) => setBody(e.target.value)}> 
            </textarea>
            <button type="submit">Create Post</button>
         </form>
      </div>

   </>
  );
}

export default CreatePost;
Enter fullscreen mode Exit fullscreen mode

Based on the code above, we needed to define a state for our title and body variables. To add a new data point to an endpoint with Axios, use the .post() method. As the second argument to the .post() method, you must include an object property containing the data you want to add. To handle the response, you must once again use the .then() and .catch() methods.

You must create an HTML form element with two input tags, title and body, that contain the data that will be added to our state variables. You must also include a handler function called "handleSubmitPost" that stores the information obtained from the input tags. When you submit the form, a new instance is created in the Posts database with the new data.

How to use Axios to make DELETE Request

To remove data from an endpoint's resource, use the HTTP DELETE method. The .delete () method provided by Axios allows us to easily complete this HTPP request.

Examine the following code:

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

const RemovePost = () => {

  const [post, setPost] = useState([])

  function deletePost(id) {
    axios
      .delete(`https://jsonplaceholder.typicode.com/posts/${id}`)
      .then((response) => {
         if (response.status === 200) {
          setPosts(
             posts.filter((post) => {
             return post.id !== id;
         })
      );
   } else {
      return;
   }
  }

   return (
   <div className="post__container">
      {posts.map((post) => {
         return (
            <div className="post__parent" key={post.id}>
               {/* ... */}
               <div className="button">
                  <div className="delete-btn" 
                    onClick={() => deletePost(post.id)}>
                     Delete
                  </div>
               </div>    
            </div>
         );
      })}
   </div>
   );
};

export default RemovePost;
Enter fullscreen mode Exit fullscreen mode

When the delete button is pressed, the deletePost handler is called. This returns the id of the post to be deleted from the resource, but in order to completely remove the post from the UI, we must use the JavaScript array's filter method.

To ensure that our DELETE request was successful, we use the .then() method.

Key Differences between the Fetch API and Axios

Compatibility with Web Browsers :
Axios is compatible with a wide range of browsers, including older browsers such as Internet Explorer 11. Fetch, on the other hand, only works with Chrome 42 and up, Firefox 39 and up, Edge 14 and up, and Safari 10.3 and up.

Conversion of JSON Data :
Handling JSON data with the Fetch API is a two-step process. That is, whenever you make an HTTP request, you must call the .json() function on the response object. Unlike Axios, it automatically transforms JSON data with no manual intervention.

Installation :
Axios is a third-party package, so you must install it in your projects whenever you need it, whereas Fetch is a built-in function in JavaScript, so no installation is required.

Download Progress :
An HTTP request can sometimes take a long time to complete. In this case, the Axios library includes an Axios Progress Bar module to implement a nice progress indicator, but the Fetch API lacks progress bar support.

Interceptors for HTTP :
Because of its built-in feature called the HTTP Interceptor, the Axios library comes in handy when attempting to intercept HTTP requests, but the Fetch method by default does not provide a way to intercept requests.

Conclusion

Thus far, so good. We've learned in simple terms what APIs are and why they're important in software development.

The Fetch and Axios methods are both extremely fast and convenient methods for consuming APIs, with both having advantages and disadvantages, as we learned in the "Differences" section.

I recommend that you consume your APIs using either of the two methods. You should stick to the method that works best for you.

If you liked my article and found it useful, please leave a tip. Your contribution would enable me to continue producing high-quality articles for you.

Image description

Thank you for your continued support, and I look forward to providing you with more useful content in the future.

Top comments (1)

Collapse
 
kgaber985 profile image
Kareem Gaber

Best tutorial I've seen in the dev community, thank you