I’m trying to fetch data and then get my React App to map through the data to render each product on the page.
However it fails to find the data to perform the .map()
and I assume that’s because the fetch
hasn’t completed when it starts looking for the data.
How can I tell the map to occur after the data has been fetched? Here is an example of my code trying to get this working:
import React, { useState, useEffect } from 'react'
const App = () => {
const [productData, getproductData] = useState([]);
useEffect(() => {
fetchData();
}, []);
const fetchData = async() => {
fetch('https://dummyjson.com/products?limit=0')
.then((res) =>
res.json())
.then((response) => {
console.log(response);
getproductData(response);
})
}
return (
<div className='products'>
{productData.products.map(product => (
<div className='product' key={product.id}>
<div className='productInfo'>
<div className='productTitle'>
<div className='productBrand'>{product.brand}</div>
<div className='productName'>{product.title} </div>
</div>
</div>
</div>
))}
</div>
)
}
export default App
3
Answers
{productData.length > 0 && productData.products.map(...)}
Before fetching data, productData.products is undefined.
Replace
productData.products.map
toproductData.products?.map
will be helpful.And in this code snippet:
I think
getproductData(response.data)
will be correct.Thanks.
the issue arises because
productData.products
is undefined initially before the data is fetched. To handle this, you can add a check to ensure productData.products exists before map over it.{productData.products && productData.products.map(...)}
or you can also use
{ productData?.products.map(...)}