Use ReactJS to Fetch and Display Data from API - 5 Simple Steps - GUVI Blogs (2024)

In this blog, we’ll learn how to fetch and display data from APIs and use it in a ReactJS app. There are multiple ways to fetch data in a React application, and we’ll walk you through those methods. With the help of APIs, we can fetch the data from servers and display it in our application. Let’s first understand what an API is.

API stands for “Application Programming Interface”, which is a method of communication between different applications. ReactJS is an open-source JavaScript-based library developed by Facebook used to create web applications’ user interfaces. As ReactJS is dynamic in nature, we can get the data using APIs and display it in our application.

To render some data in our front end, we either need a backend to store our data and then make use of the data, or we can simply use APIs to have some mock data while building an application.

When we use APIs, we don’t need a backend and are also not required to build anything from scratch. Mostly, we use the REST API or the GraphQL API to access the data added to the server. Before we get into depth, we should understand how an API works.

Table of contents

  1. How does an API work?
  2. Methods to Fetch and Display Data from API:
  3. Using JavaScript Fetch API
  • Step 1. Create a React Application
  • Step 2. Change your Project Directory
  • Step 3. Access the API Endpoint
  • Step 4. Import the useState() Hook and Set it to Hold Data
  • Step 5. Create a FetchInfo() Callback Function to Fetch and Store Data
  • Output
  • Using Axios Library
    • Step 1. Create a React Application
    • Step 2. Change your Project Directory
    • Step 3. Install the Axios Library with npm or yarn
    • Step 4. Access the API Endpoint
    • Step 5. Import the Axios and useState() Hook and Set it to Hold Data
    • Step 6. Create a FetchInfo() Callback Function to Fetch and Store Data
    • Output:
  • Summing Up
  • FAQs
    • Q1. How to fetch data from API and display in JS?
    • Q2. How to display and extract JSON data from an API?
    • Q3. What is a fetch API in JavaScript?

    How does an API work?

    The workings of an API are very easy to understand. Here’s an example, say we want to build a new application but don’t have our own backend. Now, to display the news in our application, we need some third-party APIs to access their backend server and display the data in our app.

    Now, there are three things we must have noted: an application, a server, and an API. Most times, the API is in between the app and server because whenever the client requests the data, the API makes a GET request to the server and sends that back to the application for display.

    If you would like to explore ReactJS through a Self-paced course, try GUVI’s ReactJS Self-paced certification course.

    Methods to Fetch and Display Data from API:

    We commonly use a Web API called REST, or REpresentational State Transfer API, which consists of HTTP methods to fetch data from the server and display it in the application. A REST API has several methods, which are discussed further below:

    1. GET: This method is used to fetch data from a server endpoint.
    2. POST: This method is used to post the data to a server endpoint.
    3. DELETE: This method is used to delete the data from a server endpoint.
    4. 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. To fetch the data, we use the GET method.

    The different ways of Fetching the data in a React application are given below:

    • Using React Hooks
    • Using JavaScript Fetch API
    • Using async/await
    • Using Axios library
    • Using React query

    For now, we’ll only discuss the two ways of fetching data i.e., using JavaScript Fetch API and using Axios library API.

    Here are the 6 Essential Prerequisites For Learning ReactJS you must know in order to be proficient in ReactJS.

    Using JavaScript Fetch API

    The JavaScript Fetch API is an inbuilt browser’s native API that gives an easy interface to fetch the data from the network. The simplest way to use fetch() is by taking one argument and the path from where the data is to be fetched and then returning a promise in a JSON object.

    In this example, we are going to use mock data provided freely by JSONplaceholder in JSON format. We are going to use the user’s endpoint from that API i.e., https://jsonplaceholder.typicode.com/users.

    See the below steps to implement and use Fetch API to fetch the data in a react app.

    Step 1. Create a React Application

    npx create-react-app demo

    Step 2. Change your Project Directory

    cd demo

    Step 3. Access the API Endpoint

    Now, as done in the above method 1, where we’ll also access the API endpoint and store it in a const variable so that we can use it anytime and anywhere.

    const url = “https://jsonplaceholder.typicode.com/users”;

    Step 4. Import the useState() Hook and Set it to Hold Data

    import React, { useState } from 'react';const [data, setData] = useState([])

    Step 5. Create a FetchInfo() Callback Function to Fetch and Store Data

    We will create a callback function that will store the user’s data and then use the useEffect() hook to make the function run every time the page loads.Now we get the data from the API using the fetch() method in the data variable.

    const fetchInfo = () => { return fetch(url) .then((res) => res.json()) .then((d) => setData(d)) }useEffect(() => {fetchInfo();}, [])

    Now your App.js file should look like the below:

    import "./App.css";import React, { useState, useEffect } from "react";function App() { const url = "https://jsonplaceholder.typicode.com/users"; const [data, setData] = useState([]); const fetchInfo = () => { return fetch(url) .then((res) => res.json()) .then((d) => setData(d)) } useEffect(() => { fetchInfo(); }, []); return ( <div className="App"> <h1 style={{ color: "green" }}>using JavaScript inbuilt FETCH API</h1> <center> {data.map((dataObj, index) => { return ( <div style={{ width: "15em", backgroundColor: "#35D841", padding: 2, borderRadius: 10, marginBlock: 10, }} > <p style={{ fontSize: 20, color: 'white' }}>{dataObj.name}</p> </div> ); })} </center> </div> );}export default App;

    Output

    The output for the above example is as follows:

    Use ReactJS to Fetch and Display Data from API - 5 Simple Steps - GUVI Blogs (2)

    Using Axios Library

    Axios is an online HTTP library running on node.js that allows us to make various HTTP requests to a given server endpoint. If we see it working, then it uses the http module on the server side, whereas it uses XMLHttpRequests on the browser side. For this example, we are going to use the GET method to fetch and display the data in our React application. Here we don’t need to convert the result into a JSON object; it already comes as a JSON object.

    See the below steps for the installation of the Axios library and the fetching process of the data in a react app.

    Step 1. Create a React Application

    The first thing to do is create a React application from scratch using the below npx command. Write or copy/paste the following to create a react app in your desired directory and name the project of your choice. For this example, we have created a project called “demo.”

    npx create-react-app demo

    Step 2. Change your Project Directory

    Once the project is created, change the directory to where the app folder is created.

    cd demo

    Step 3. Install the Axios Library with npm or yarn

    For using the axios library, we need to install that and we can do that using two ways i.e, either install using NPM or Yarn. Install it with any one of your choice or requirements.

    npm install axios

    Or

    yarn add axios

    Step 4. Access the API Endpoint

    Now, as done in the above method 1, where we’ll also access the API endpoint and store it in a const variable so that we can use it anytime and anywhere.

    const url = “https://jsonplaceholder.typicode.com/users”;

    Step 5. Import the Axios and useState() Hook and Set it to Hold Data

    Import the installed axios library to the App.js file and also the useState() hook tohold the data in a variable.

    import React, { useState } from 'react';import axios from 'axios';const [data, setData] = useState([])

    Step 6. Create a FetchInfo() Callback Function to Fetch and Store Data

    In this method also, we will create a callback function that will store the user’s data and then use the useEffect() hook to make the function run every time the page loads.

    const fetchInfo = () => { return axios.get(url) .then((response) => setUser(response.data));}useEffect(() => { fetchInfo(); }, [])

    Now your App.js file should look like below:

    import "./App.css";import React, { useState, useEffect } from "react";import axios from "axios";function App() { const url = "https://jsonplaceholder.typicode.com/users"; const [data, setData] = useState([]); const fetchInfo = () => { return axios.get(url).then((res) => setData(res.data)); }; useEffect(() => { fetchInfo(); }, []); return ( <div className="App"> <h1 style={{ color: "green" }}>using Axios Library to Fetch Data</h1> <center> {data.map((dataObj, index) => { return ( <div style={{ width: "15em", backgroundColor: "#CD8FFD", padding: 2, borderRadius: 10, marginBlock: 10, }} > <p style={{ fontSize: 20, color: 'white' }}>{dataObj.name}</p> </div> ); })} </center> </div> );}export default App;

    Output:

    The output for the above example is as follows:

    Use ReactJS to Fetch and Display Data from API - 5 Simple Steps - GUVI Blogs (3)

    Before diving into the last section, ensure you’re solid on full-stack development essentials like front-end frameworks, back-end technologies, and database management. If you are looking for a detailed Full-Stack Development career program, you can join GUVI’s Full Stack Development Career Program with placement assistance. You will be able to master the MERN stack (MongoDB, Express.js, React, and Node.js) and build real-life projects.

    Summing Up

    In this blog, we learned how to fetch data using an API in a React.js application. We hope you get a very good understanding of how an API works, how to fetch data from an API, and the different ways of fetching data using an API. Additionally, we learned how to use the inbuilt JavaScript Fetch API to fetch data and also saw how to use the Axios library, which is a better alternative to the inbuilt Fetch API.

    FAQs

    Q1. How to fetch data from API and display in JS?

    Ans.To fetch data from an API and display it in JS, you need to define a const data and store it in JSON by await response. json() method. When we get the data from API by fetch() method in the data variable; pass it to the function which will show the data fetched.

    Q2. How to display and extract JSON data from an API?

    Ans. To get JSON from a REST API endpoint, you mustsend an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept: application/json header tells the REST API server that the API client expects to receive data in JSON format.

    Q3. What is a fetch API in JavaScript?

    Ans. The Fetch API isa modern interface that allows you to make HTTP requests to servers from web browsers. If you have worked with XMLHttpRequest (XHR) object, the Fetch API can perform all the tasks as the XHR object does. In addition, the Fetch API is much simpler and cleaner.

    Use ReactJS to Fetch and Display Data from API - 5 Simple Steps - GUVI Blogs (2024)

    FAQs

    Use ReactJS to Fetch and Display Data from API - 5 Simple Steps - GUVI Blogs? ›

    To Get data using the Fetch API in JavaScript, we use the fetch() function with the URL of the resource we want to fetch. By default, the fetch method makes the Get request.

    How to fetch data from API and display in JS? ›

    To Get data using the Fetch API in JavaScript, we use the fetch() function with the URL of the resource we want to fetch. By default, the fetch method makes the Get request.

    How do you fetch an object from API in React? ›

    Inside useEffect() , we fetch our data by sending a request with the API key. The response comes back in JSON (JavaScript Object Notation). In the return statement, we process the received photos by utilizing a map() function to iterate through each item.

    How to fetch data from API in table format in React js? ›

    Fetching Data with React Query Hooks

    React Query provides several hooks for fetching data, but the most commonly used one is useQuery. This hook is used to fetch data from an API and provide it to your React component. It also tracks the loading and error states, making it easier to provide feedback to the user.

    What are the steps in fetch API? ›

    fetch API in JavaScript with Examples
    1. fetch('url') // api for the get request . ...
    2. let options = { method: 'POST', headers: { 'Content-Type': 'application/json;charset=utf-8' }, body: JSON.stringify(data) }
    3. fetch("https://example.com", { credentials: "include", });
    7 days ago

    How to fetch and display JSON data in HTML using JavaScript? ›

    A web browser.
    1. Step 1: Create Your HTML Structure. Let's start by setting up the HTML structure for displaying JSON data. ...
    2. Step 2: Create Your JSON Data. Now, let's create a simple JSON file with the data you want to display. ...
    3. Step 3: Write JavaScript to Populate the HTML. ...
    4. Step 4: Test Your Web Page.
    Oct 26, 2023

    How to fetch data from an API and render it into cards using JavaScript? ›

    To fetch data from a sample API and render it in a card using JavaScript and CSS, you can follow these steps:
    1. Step 1: Create an HTML structure for the card and include a container where you'll render the data.
    2. Step 2: Create a CSS file ( styles. css ) to style the card.
    3. Step 3: Create a JavaScript file ( script.
    Sep 13, 2023

    How do I extract data from API in React? ›

    Modern API data-fetching methods in React
    1. Rendering the post data with fetch()
    2. Extracting the fetching logic.
    3. Rendering a single post with fetch()
    4. Problem with API calls inside useEffect.
    5. The useEffect race condition.
    6. Using the Fetch API for POST requests.
    Mar 1, 2024

    How to use API in ReactJS? ›

    Finally, I will point you towards more advanced examples so you can continue to grow!
    1. Create a Basic Project Structure. Make a new folder. I named mine react-api-call . ...
    2. Add React Component. Back in the terminal run these two commands: npm init -y : Creates an npm package in our project root.
    Mar 7, 2023

    How do I fetch data from API in react admin? ›

    Whenever react-admin needs to communicate with your APIs, it does it through an object called the dataProvider . The dataProvider exposes a predefined interface that allows react-admin to query any API in a normalized way. For instance, to query the API for a single record, react-admin calls dataProvider.

    How to fetch data from API in React functional component? ›

    Fetching Data from APIs in React. js
    1. Set Up a New React. js Project.
    2. Create a Component for Fetching Data.
    3. Perform the API Request.
    4. Handle the API Response.
    5. Display the Data in the Component.
    6. Handle Loading and Error States.
    Aug 2, 2023

    How to display table data in React? ›

    In the src directory, create a new file called Table. js and add the following code: import React, { Component } from 'react'; class Table extends Component { render() { const { data } = this. props; return ( <table> <thead> <tr> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> {data.

    What are the 5 steps of the fetch execute cycle? ›

    • Fetch. The CPU collects an instruction and prepares it for decoding. ...
    • Decode. The decoder in the control unit works out (decodes) what to do with the instruction. ...
    • Execute. The Arithmetic Logic Unit (ALU) then executes the decoded instructions. ...
    • Store. Send and write the results back in main memory.

    How to use Fetch API in React? ›

    Making APIs in React with Fetch API

    It uses JavaScript promises which make working with requests and responses easier. To make a request, you simply call the fetch() method, pass in the URL to fetch from, and then handle the response when it resolves. This is much simpler than working directly with XMLHttp Requests.

    How to fetch the data from API? ›

    In this example, we define the API endpoint for user data ( https://api.example.com/users/123 ). The fetch function is used to make the GET request, and we handle the response by checking if it's okay using the response. ok property. If the response is okay, we convert it to JSON and process the user data.

    How to fetch data from API and display in HTML in React js? ›

    Approach 1: Using JavaScript fetch() method

    js and styling component in App. css. From the API we have target “id”, “name”, “username”, and “email” and fetch the data from API endpoints. We will use the fetch method to get the data from API.

    How to fetch data from database and display in JavaScript? ›

    Step 1 — Getting Started with Fetch API Syntax
    1. fetch(url) . then(function() { // handle the response })
    2. fetch(url) . then(function() { // handle the response }) . catch(function() { // handle the error });
    3. // ... fetch(url, fetchData) . then(function() { // Handle response you get from the API });
    Dec 10, 2021

    How to use the JavaScript fetch API to put data? ›

    How to use Fetch API with the PUT method
    1. Prepare the data you want to update. Before making the API request, you need to prepare the data you want to send to the server. ...
    2. Convert the data to a JSON string. Before sending the data to the server, we need to convert it into a JSON string. ...
    3. Use the Fetch API to make the request.
    Apr 26, 2023

    How to fetch data from API and display in React js using axios? ›

    By using the `axios. get()` method to fetch data from an API and updating the state with the response data, we can easily display the fetched data in our React components. In conclusion, using Axios with React is a powerful combination for making HTTP requests and fetching data from APIs.

    Top Articles
    Fireproof Balloon Experiment - Demonstration of Balloon experiment, Applications, and FAQs
    FLOKI price today, FLOKI to USD live price, marketcap and chart | CoinMarketCap
    Visitor Information | Medical Center
    The Atlanta Constitution from Atlanta, Georgia
    Free Atm For Emerald Card Near Me
    Davante Adams Wikipedia
    Find All Subdomains
    Northern Whooping Crane Festival highlights conservation and collaboration in Fort Smith, N.W.T. | CBC News
    Visustella Battle Core
    Miami Valley Hospital Central Scheduling
    Brutál jó vegán torta! – Kókusz-málna-csoki trió
    R/Afkarena
    People Portal Loma Linda
    U/Apprenhensive_You8924
    Les Schwab Product Code Lookup
    No Hard Feelings Showtimes Near Cinemark At Harlingen
    5 high school volleyball stars of the week: Sept. 17 edition
    Hilo Hi Craigslist
    Best Forensic Pathology Careers + Salary Outlook | HealthGrad
    Union Ironworkers Job Hotline
    Hewn New Bedford
    Aol News Weather Entertainment Local Lifestyle
    PCM.daily - Discussion Forum: Classique du Grand Duché
    Happy Homebodies Breakup
    Hdmovie2 Sbs
    Booknet.com Contract Marriage 2
    Cardaras Funeral Homes
    Webworx Call Management
    1636 Pokemon Fire Red U Squirrels Download
    Shoe Station Store Locator
    Winterset Rants And Raves
    Allegheny Clinic Primary Care North
    Utexas Baseball Schedule 2023
    6143 N Fresno St
    Nacho Libre Baptized Gif
    Instafeet Login
    Game8 Silver Wolf
    Los Garroberros Menu
    Woodman's Carpentersville Gas Price
    The Best Restaurants in Dublin - The MICHELIN Guide
    Craigslist Tulsa Ok Farm And Garden
    Craigs List Palm Springs
    Karen Wilson Facebook
    Unblocked Games Gun Games
    Shipping Container Storage Containers 40'HCs - general for sale - by dealer - craigslist
    Unitedhealthcare Community Plan Eye Doctors
    Arch Aplin Iii Felony
    Gw2 Support Specter
    Uncle Pete's Wheeling Wv Menu
    Tweedehands camper te koop - camper occasion kopen
    Laurel Hubbard’s Olympic dream dies under the world’s gaze
    Mast Greenhouse Windsor Mo
    Latest Posts
    Article information

    Author: Lilliana Bartoletti

    Last Updated:

    Views: 5762

    Rating: 4.2 / 5 (73 voted)

    Reviews: 88% of readers found this page helpful

    Author information

    Name: Lilliana Bartoletti

    Birthday: 1999-11-18

    Address: 58866 Tricia Spurs, North Melvinberg, HI 91346-3774

    Phone: +50616620367928

    Job: Real-Estate Liaison

    Hobby: Graffiti, Astronomy, Handball, Magic, Origami, Fashion, Foreign language learning

    Introduction: My name is Lilliana Bartoletti, I am a adventurous, pleasant, shiny, beautiful, handsome, zealous, tasty person who loves writing and wants to share my knowledge and understanding with you.