In this blog, we’ll look at how to retrieve and display data from APIs for use in a ReactJS app. We’ll go over the various methods for fetching data in a React application. APIs allow us to fetch data from servers and display it in our application. Let’s first define what an API is.
API stands for “Application Programming Interface,” which is a means of communication between different applications. ReactJS is an open-source JavaScript-based library developed by Facebook for creating web application user interfaces. Because ReactJS is dynamic, we can access data through APIs and display it in our application.
To render some data in our front end, we either need a backend to store the data and then use it, or we can simply use APIs to create some mock data while developing an application.
When we use APIs, we don’t need a backend and don’t have to create anything from scratch. We mostly use the REST API or the GraphQL API to access the server’s data. Before we get into the details, we should understand how an API works.
How does an API work?
An API (Application Programming Interface) serves as a bridge between various software applications, allowing them to communicate with one another. When you retrieve data from an API, your application sends a request to the server, which then returns the requested data. This data is typically in JSON format and can be easily manipulated in JavaScript.
Methods to Fetch and Display Data from API:
We commonly use a Web API known as REST, or Representational State Transfer API, which consists of HTTP methods for retrieving data from the server and displaying it in the application. A REST API consists of several methods, which are discussed further below:
- GET: This method is used to fetch data from a server endpoint.
- POST: This method is used to post the data to a server endpoint.
- DELETE: This method is used to delete the data from a server endpoint.
- PUT: This method is used to update or modify the data from a server endpoint.
Now as you have understood all the methods of the API, we can now move on to how the data is fetched from the server. We retrieve data using the GET method.
The various methods of fetching data in a React application are listed below:
- Using React Hooks
- Using JavaScript Fetch API
- Using async/await
- Using Axios library
- Using React query
For now, we’ll only cover two methods for fetching data: JavaScript Fetch API and Axios library API.
Using JavaScript Fetch API
The JavaScript Fetch API is a built-in browser native API that provides a simple interface for retrieving data from the network. The simplest way to use fetch() is to pass in one argument and the path from which the data should be fetched, and then return a promise in the form of a JSON object.
The Fetch API provides a simple interface for fetching resources. It allows you to make network requests similar to XMLHttpRequest (XHR).
In this example, we will use JSONplaceholder’s freely available mock data in JSON format. We will use the user endpoint from that API, which is https://jsonplaceholder.typicode.com/users.
Step 1. Create a React Application
First, create a new React application using Create React App
npx create-react-app fetch-api-example
Step 2. Change your Project Directory
Navigate into your project directory.
cd fetch-api-example
Step 3. Access the API Endpoint
Identify the API endpoint you want to fetch data from. For example, we’ll use a public API endpoint that provides random user data.
const url = “https://jsonplaceholder.typicode.com/users”;
Step 4. Import the useState() Hook and Set it to Hold Data
In your App.js
file, import the useState
hook from React.
import React, { useState, useEffect } from 'react';
Step 5. Create a FetchInfo() Callback Function to Fetch and Store Data
Create a function to fetch data from the API and store it in the state.
const App = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
<h1>Fetched Data</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
};
export default App;
Output
The above code will display the fetched data in a list format.
Using Axios Library
Axios is an online HTTP library that runs on node.js and allows us to send various HTTP requests to a specific server endpoint. If we see it working, it uses the http module on the server side and XMLHttpRequests on the client side. For this example, we’ll use the GET method to retrieve and display data in our React application. We don’t need to convert the result into a JSON object because it already comes as one.
Step 1. Create a React Application
First, create a new React application using Create React App.
npx create-react-app axios-api-example
Step 2. Change your Project Directory
Navigate into your project directory.
cd axios-api-example
Step 3. Install the Axios Library with npm or yarn
Install Axios using npm or yarn.
npm install axios or yarn add axios
Step 4. Access the API Endpoint
Identify the API endpoint you want to fetch data from.
const url = “https://jsonplaceholder.typicode.com/users”;
Step 5. Import the Axios and useState() Hook and Set it to Hold Data
In your App.js
file, import Axios and the useState
hook.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
Step 6. Create a FetchInfo() Callback Function to Fetch and Store Data
Create a function to fetch data from the API and store it in the state.
const App = () => {
const [data, setData] = useState([]);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/users.')
.then(response => setData(response.data));
}, []);
return (
<div>
<h1>Fetched Data</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
};
export default App;
Output
The above code will display the fetched data in a list format.
Summing Up
Fetching and displaying data from an API in a React application can be done efficiently using either the Fetch API or Axios library. Both methods are straightforward and can be implemented with a few lines of code. Choose the method that best suits your needs and preferences.
FAQs
Q1. How to fetch data from API and display in JS?
To fetch data from an API and display it in JavaScript, you can use the Fetch API or Axios library to make a network request, retrieve the data, and then update the state to display the data in your UI.
Q2. How to display and extract JSON data from an API?
You can extract JSON data from an API by making a network request using the Fetch API or Axios, then parsing the JSON response and updating your state or UI with the extracted data.
Q3. What is a fetch API in JavaScript?
The Fetch API is a modern interface that allows you to make network requests similar to XMLHttpRequest. It provides a more powerful and flexible feature set, including promises and an easier syntax for fetching resources.
By following these steps, you can easily fetch and display data from any API in your React application, making your app more dynamic and data-driven.
Leave a response to this article by providing your insights, comments, or requests for future articles.
Share the articles with your friends and colleagues on social media