I am rendering a product list from dummyjson
getting response from api
but showing products.map() is not a function
const fetchData = async () => {
const response = await fetch("https://dummyjson.com/products");
const data = await response.json();
return setProducts(data);
}
useEffect(() => {
fetchData();
},[])
console.log(products)
return (
<div>
<ul>
{products.map((product, index) => {
return (
<li key={index}>
<h2>{product.title}</h2>
</li>
);
})}
</ul>
</div>
)
2
Answers
Your
data
is an object. What you want to do is extract products from the JSON response, so infetchData
method you should call:setProducts(data.products)
.The api returns an object with a property
products
which contains the products array, so you need to doAlternatively, you could store just the products array in state like so, and you can keep your existing map code.