Display and Retrieve Data from an API using Modern Fetch API in React JS

Posted by

Fetch and Display data from API in React JS

How to Fetch and Display data from API in React JS with Modern Fetch API

When working with React JS, it is common to need to fetch and display data from an external API. The modern Fetch API provides a simple and elegant way to make HTTP requests and handle responses, making it a great choice for fetching data in React applications.

Here’s a step-by-step guide on how to fetch and display data from an API in React JS using the modern Fetch API:

Step 1: Create a React Component

First, create a new React component that will be responsible for fetching and displaying the data from the API. You can create a new file for this component, or add it to an existing file if you already have a React application set up.

“`javascript
import React, { useState, useEffect } from ‘react’;

function DataComponent() {
const [data, setData] = useState(null);

useEffect(() => {
fetchData();
}, []);

const fetchData = async () => {
const response = await fetch(‘https://api.example.com/data’);
const result = await response.json();
setData(result);
};

return (

{data ? (

Data from API:

{data}

) : (

Loading…

)}

);
}

export default DataComponent;
“`

Step 2: Use the Component in Your Application

Once you have created the component for fetching and displaying the data, you can use it in your application by importing it and adding it to your component hierarchy.

“`javascript
import React from ‘react’;
import DataComponent from ‘./DataComponent’;

function App() {
return (

My React App

);
}

export default App;
“`

Step 3: Display the Data

Now, when you run your React application, the DataComponent will fetch the data from the API and display it in the browser. If the data is not yet available, the component will display a “Loading…” message until the data has been fetched.

With the modern Fetch API, fetching and displaying data from an API in a React JS application is simple and efficient. By following this guide, you can easily integrate data from external APIs into your React applications.

0 0 votes
Article Rating
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@atifhassan8098
10 months ago

if i want to fetch the data from my local API same i have to do?

@muhammadarslan78676
10 months ago

Thanks man, for this great example!

@muhammadzohaib543
10 months ago

Sir, whats the best ? axios or like this ?

@user-vj8pt2yf7f
10 months ago

can you explain what's the value in List and index parameter ?

@lalitadaharwal2487
10 months ago

Axios is better way for fetch api