To fetch data from an API in React, you can use the built-in Fetch API or popular libraries like Axios or jQuery. Here is an example of using the Fetch API in a React component:
npm install axios
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const FetchData = () => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
setData(response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []);
return (
<div>
{data ? (
<div>
<h1>Data from API:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
) : (
<p>Loading...</p>
)}
</div>
);
};
export default FetchData;
In the useEffect
hook, the fetchData
function uses Axios to make a GET request to the specified API endpoint. It then sets the retrieved data in the component's state using the setData
function.
In the component's return, it checks if the data has been fetched successfully. If so, it displays the data using JSON.stringify
, otherwise it displays a loading message.
You can then include the FetchData
component in your main App component or any other component where you want to display the fetched data.
Your data should now be fetched from the API and displayed in your React application using the Fetch API.