Fetching data from an API in ReactJS is a common and crucial task in modern web development. Retrieving data from an API allows you to receive real-time updates dynamically and efficiently. In this tutorial, we will be fetching data from a URL.
Prerequisites
React and Vite
Let's fetch Data
We are using the Data USA API in this tutorial, which will provide us with the population of a country, the year of the population data, and the country's name.
import { useEffect, useState } from 'react'
const DataFetch = () => {
const [data, setData] = useState([])
const fetchData = async () => {
const response = await fetch('https://datausa.io/api/data?drilldowns=Nation&measures=Population')
.then(response =>
response.json())
.then(response=>
setData([response.data[0]]))
.catch(err =>
console.log(err))
return response;
}
useEffect(()=> {
fetchData();
}, [])
return (
<div className="flex flex-col justify-center items-center mt-2 bg-black text-blue-500">
<h1>Data fetched</h1>
<div className='mt-3'>
{data.map((item, index) => (
<div key={index} >
<ul key={item.id}>
<li>Poppulation {item.Population}</li>
<li>Year {item.Year}</li>
<li>Country {item.Nation}</li>
</ul>
</div>
))}
</div>
</div>
)
}
export default DataFetch
Note: Import it in your App component to render this component. you see the following example.
import DataFetch from "./components/DataFetch"
function App() {
return (
<>
<DataFetch />
</>
)
}
export default App
Run your application
Type npm run dev
to run your react+vite application and open http://localhost:5173/
Let's fetch some dummy products Data.
import { useState, useEffect } from 'react'
import './App.css'
function App() {
const [products, setProducts] = useState([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState(false)
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true)
const response = await fetch('https://dummyjson.com/products')
const data = await response.json()
setProducts(data.products)
setLoading(false)
} catch (error) {
setError(true)
setLoading(false)
}
}
fetchData()
},[])
return (
<>
<div>
{loading && <h1>Loading...</h1>}
{error && <h1>Error...</h1>}
<h1>API Fetching</h1>
<div className=''>
<ul>
{products.map((product) => (
<li key={product.id}>
<p>Title: {product.title}</p>
<p>Price: {product.price}</p>
</li>
))}
</ul>
</div>
</div>
</>
)
}
export default App
How handle Professionaly API in React?
In this process, you need to modify your API fetching methods and hooks. You can refer to the following code. We have utilized Immediately Invoked Function Expressions (IIFE) to handle this task more efficiently.
import { useEffect, useState } from 'react'
const DataFetch = () => {
const [data, setData] = useState([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState(false)
useEffect(() => {
(async ()=> {
try {
setLoading(true)
setError(false)
const response = await fetch('https://datausa.io/api/data?drilldowns=Nation&measures=Population')
const data = await response.json()
setData([data.data[0]])
setLoading(false)
} catch (error) {
setLoading(false)
setError(true)
}
})()
},[])
return (
<div className="flex flex-col justify-center items-center mt-2 text-blue-500">
{loading && <h1>Loading...</h1>}
{error && <h1>Error occured</h1>}
<h1>Data fetched</h1>
<div className='mt-3'>
{data.map((item, index) => (
<div key={index} >
<ul key={item.id}>
<li>Poppulation {item.Population}</li>
<li>Year {item.Year}</li>
<li>Country {item.Nation}</li>
</ul>
</div>
))}
</div>
</div>
)
}
export default DataFetch