Modern technology gives us many things.

How to Consume APIs in React Using Fetch and Axios

0


An API (Application Programming Interface) is a set of protocols that allows an application to send requests to a server and receive a response.

Through APIs, you are able to integrate pieces of software into your application without the nitty-gritty work. This process of using an API in your application is generally referred to as consuming an API. For instance, if you want to display a certain location on your website, you would use the Google Maps API instead of implementing the map functionality from scratch. APIs, therefore, reduce your workload and save you time.

To learn how to consume REST APIs in React using Fetch and Axios, you will build a simple React application that gets a random fact about cats from an API when you click a button.

Types of APIs

APIs can be classified by either availability or use case. In terms of availability, APIs can be public, private, partner, or composite APIs. When classified according to their purpose, they can be database, remote, operating systems, or web APIs. In this article, we will be consuming a type of web API called a REST (Representational State) API.

REST APIs allow you to get data from a source through a URL. In React, there are several methods you can use to consume REST APIs. This article discusses the two most popular methods namely the JavaScript Fetch API and the promise-based HTTP client Axios.

MAKEUSEOF VIDEO OF THE DAY

Related: What is REST API and How Can You Grab Data for Your App or Website

Prerequisites

To follow along with this guide, you should have:

  • Basic understanding of JavaScript.
  • Basic knowledge of React, and React hooks.
  • NPM installed locally on your machine.
  • A text editor or IDE of your choice installed.

Create a React Application

First, you will need to create a React application. Copy the following command in your terminal to set up a React development environment.

npx create-react-app catfact

Once the command completes executing, open the catfact folder in your text editor. You will be writing your code in the App.js file in the src folder so go ahead and remove the unnecessary code.


import "./App.css";
function App() {
return (
<div className="App">
<h2>Press the button for a random cat fact!</h2>
<hr />
<button>Get Cat fact</button>
</div>
);
}
export default App;

Next, create a simple UI that will use to display the random cat fact.

In app.js

import './App.css';
function App() {
return (
<div className="App">
<h2>Press the button for a random cat fact!</h2>
<hr/>
<button>Get Cat fact</button>
</div>
);
}
export default App;

To style your app, add the following code to the app.css file.

@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@700;500&display=swap');
.App {
font-family: 'Playfair Display', serif;
margin: 20px 15vw;
}
h2 {
font-family: 'Playfair Display', serif;
font-weight: 700;
font-size: 3em;
}
button {
padding: 1em 1.2em;
border: none;
font-size: 1em;
background-color: #131212;
color: #ffffff;
border-radius:0.5em;
cursor: pointer;
}
button:hover{
background-color:#3b3b3b;
}

Your application should now look like this.

React application UI showing a heading and 'cat fact' button

In the next steps, you will fetch data from the API and display it in the application.

Related: How to Create Your First React App With JavaScript

Consuming REST APIs Using Fetch

Fetch API is an interface that allows you to get resources from an API through HTTP requests. The fetch() method receives the URL of the path to the resource as a mandatory argument and returns a promise that can resolve to a response.

The basic syntax of the fetch() method is as follows:

fetch(‘url to resource’)
.then(response => // handle response)
.catch(err => // handle error)

Implementing Fetch API

In React, the Fetch API is used the same way it’s used in plain JavaScript.

fetch("https://catfact.ninja/fact")
.then(response => response.json())
.then(data => // handle data)
.catch(err => // handle error)

In the first line in the code above, you are passing in the API URL to the fetch() method. fetch() returns an HTTP response which is converted to JSON using the json() method. In the third line, you get access to the data which you can then use in the application. Finally, the catch block allows you to handle errors gracefully.

To implement the fetch request in the app component, you will use React hooks. By using the useEffect hook, your application will make the request once the component loads and the useState hook will create and update the state of the component. Keeping track of state ensures that the component re-renders when the fetch API returns the response.

Related: Hooks: The Hero of React

import useState and useEffect.
import { useEffect, useState } from 'react'

Create a state to hold the cat fact and the function to update it.

const [fact, setFact] = useState('')

Next, create a function to make the GET request to the API and call it in the useEffect hook.

const fetchFact = () => {
fetch("https://catfact.ninja/fact")
.then((response) => response.json())
.then((data) => setFact(data.fact));
}
useEffect(() => {
fetchFact()
}, []);

Your app.js file should now look like this:

import "./App.css";
import { useEffect, useState } from "react";
function App() {
const [fact, setFact] = useState("");
const fetchFact = () => {
fetch("https://catfact.ninja/fact")
.then((response) => response.json())
.then((data) => setFact(data.fact));
}
useEffect(() => {
fetchFact()
}, []);
return (
<div className="App">
<h2>Press the button for a random cat fact!</h2>
<hr />
<button>Get Cat fact</button>
<p>{fact}</p>
</div>
);
}
export default App;


You should now be able to see a random fact about cats displayed in your browser.

Next, write code to display a random fact when the button is clicked.

Modify the button to include an onClick event and its handler function.

<button onClick= {() => handleClick()}>Get Cat fact</button>

Define the handleClick() function as shown below.

const handleClick = () => {
fetchFact()
}

Now, when you click the button, the handleClick() function will call fetchData() which will perform the API request and update the state with a new random fact. Consequently, the application UI will update to display the current fact.

Consuming REST APIs Using Axios

Instead of fetch(), you can consume APIs with Axios. Like fetch(), Axios allows you to make requests to an API endpoint. However, there are several differences between the two.

  • Axios automatically returns the response in JSON while you have to convert it to JSON when using the Fetch API.
  • Axios requires only one .then() callback unlike the Fetch API.
  • Axios is compatible with major browsers while Fetch is only supported in Chrome 42+, Edge 14 +, Firefox 39+, and Safari 10+

Implementing Axios

Install Axios by running the following command.

npm install axios

After the installation is completed, import the Axios package into your app component and modify the fetchFact() function to use it.

import axios from ‘axios’
const fetchFact = () => {
axios.get("https://catfact.ninja/fact").then((response) => {
setFact(response.data.fact)
});
}

That’s it! Your application should be displaying a random cat fact when it loads in the browser and when you click the button.

React application displaying a random cat fact

More Uses for APIs With React

You can consume REST APIs in React using various methods. In this tutorial, you learned how to use Fetch and Axios to fetch a random fact from a REST API. The use cases of APIs in real world applications is endless.

For example, through payment APIs like Stripe and PayPal, stores can easily handle customer transactions online without needing to implement the functionality themselves. Therefore, even less technology savvy users can build useful applications that serve their needs.


Biometrics Scanner
What Is API Authentication and How Does It Work?

How do you prove that the person wanting to access important data is who they say they are? That’s where API authentication comes in…

Read Next


About The Author



Source link

Leave A Reply

Your email address will not be published.