Fetching Data from APIs
Fetching and displaying data from an API is a common task in many web applications. In a React application, we can use the fetch
API or libraries like axios
to retrieve data from an external source.
Here's an example of how to fetch data from an API in a React component:
JAVASCRIPT
1import React, { useState, useEffect } from 'react';
2
3function DataComponent() {
4 const [data, setData] = useState([]);
5
6 useEffect(() => {
7 const fetchData = async () => {
8 try {
9 const response = await fetch('https://api.example.com/data');
10 const data = await response.json();
11 setData(data);
12 } catch (error) {
13 console.error(error);
14 }
15 };
16
17 fetchData();
18 }, []);
19
20 return (
21 <div>
22 {data.map((item) => (
23 <div key={item.id}>{item.name}</div>
24 ))}
25 </div>
26 );
27}
28
29export default DataComponent;
xxxxxxxxxx
12
// Fetch data from an API
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchData();
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment