React.js API Integration
API Integration in React.js:
Integrating APIs into React.js applications allows you to fetch data from external sources and incorporate it dynamically into your user interface.
How to fetch data from APIs using fetch or Axios and handle asynchronous operations:
Using fetch for HTTP requests:
The fetch API is built into modern web browsers and provides a simple way to make HTTP requests.
import React, { useState, useEffect } from 'react';
function App() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error('Error fetching data:', error));
}, []);
return (
<div>
{data ? (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
) : (
<p>Loading...</p>
)}
</div>
);
}
export default App;
We use fetch to retrieve data from the API endpoint. We then use useState to manage the retrieved data and useEffect to execute the fetch operation when the component mounts.
Using Axios for HTTP requests:
Axios is a popular HTTP client library for JavaScript, widely used for making HTTP requests.First, install Axios:
npm install axios
Or
yarn add axios
Then, use Axios in your React component:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState(null);
useEffect(() => {
axios.get('https://api.example.com/data')
.then(response => setData(response.data))
.catch(error => console.error('Error fetching data:', error));
}, []);
return (
<div>
{data ? (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
) : (
<p>Loading...</p>
)}
</div>
);
}
export default App;
We use Axios's get method to fetch data from the API endpoint. The retrieved data is then stored in the component's state using useState.