How to fetch data from an API in ReactJS ?
Fetching data from an API in React JS is a common and crucial task in modern web development. Fetching data from API helps in getting real-time updates dynamically and efficiently. API provides on-demand data as required rather than loading all data.
Prerequisites:
Different ways to Fetch data from API in React
- Using JavaScript Fetch: To fetch data in react we can use JavaScript built in fetch method it allows to send http request to the api and get the data in form of promise.
- Using Axios: It is a promise based javascript library used to make different http requests with simple chaining syntax. It make the data fetching and response process easy and efficient.
These approaches are given below in detail:
Table of Content
Steps to create the React Application
Step 1: Create React Project
npm create-react-app myreactapp
Step 2: Change your directory and enter your main folder charting as
cd myreactapp
Step 3: Write code in App.js to fetch data from API and we are using the fetch function.
Project Structure:
Approach 1: Using JavaScript fetch() method
To fetch the data from api in react we can use the fetch method insde the useEffect hooks. For the data, we have used the API endpoint from http://jsonplaceholder.typicode.com/users. we have created the component in App.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. Below is the stepwise implementation of how we fetch the data from an API in React.
Example: This example uses javascript fetch to get and render the data on the webpage.
/* App.css*/
.App {
text-align: center;
/* color: Green; */
}
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
}
.item {
min-width: 33rem;
text-align: left;
}
.geeks {
color: green;
}
// App.js
import React from "react";
import "./App.css";
class App extends React.Component {
// Constructor
constructor(props) {
super(props);
this.state = {
items: [],
DataisLoaded: false,
};
}
// ComponentDidMount is used to
// execute the code
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((json) => {
this.setState({
items: json,
DataisLoaded: true,
});
});
}
render() {
const { DataisLoaded, items } = this.state;
if (!DataisLoaded)
return (
<div>
<h1> Pleses wait some time.... </h1>
</div>
);
return (
<div className="App">
<h1 className="geeks">GeeksforGeeks</h1>
<h3>Fetch data from an api in react</h3>
<div className="container">
{items.map((item) => (
<div className="item">
<ol key={item.id}>
<div>
<strong>
{"User_Name: "}
</strong>
{item.username},
</div>
<div>
Full_Name: {item.name},
</div>
<div>
User_Email: {item.email}
</div>
</ol>
</div>
))}
</div>
</div>
);
}
}
export default App;
Step to run the application:
Open the terminal and type the following command.
npm start
Output: Open the browser and our project is shown in the URL http://localhost:3000/
Approach 2: Using axios library
We can also fetch data in react with the help of axios library. Axios is a Promise based JavaScript Library use to make the http request from the browser. We will use axios.get method to fetch the data from the given api and then present it on the web pages as required using react jsx components.
Steps to install axios:
npm i axios
The updated dependencies in the package.json file are:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"axios": "^1.5.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Example: This example uses axios to get the data from the api and represent on the web page.
/* App.css*/
.App {
text-align: center;
/* color: Green; */
}
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
}
.item {
min-width: 33rem;
text-align: left;
}
.geeks {
color: green;
}
// App.js
import React from "react";
import "./App.css";
import axios from "axios"; // uimport axios
class App extends React.Component {
// Constructor
constructor(props) {
super(props);
this.state = {
items: [],
DataisLoaded: false,
};
}
// ComponentDidMount is used to
// execute the code
componentDidMount() {
axios.get(
"https://jsonplaceholder.typicode.com/users"
)
.then((res) => {
this.setState({
items: res.data,
DataisLoaded: true,
});
});
}
render() {
const { DataisLoaded, items } = this.state;
if (!DataisLoaded)
return (
<div>
<h1> Pleses wait some time.... </h1>
</div>
);
return (
<div className="App">
<h1 className="geeks">GeeksforGeeks</h1>
<h3>Fetch data from an api in react</h3>
<div className="container">
{items.map((item) => (
<div className="item">
<ol key={item.id}>
<div>
<strong>
{"User_Name: "}
</strong>
{item.username},
</div>
<div>
Full_Name: {item.name},
</div>
<div>
User_Email: {item.email}
</div>
</ol>
</div>
))}
</div>
</div>
);
}
}
export default App;
Steps to run the application:
npm start
Output: This output will be visible on http://localhost:3000/
