Working on app using reactJS, while using map function finding this error on console TypeError: data.map is not a function but the API data calling was successful found in console.log but to display data on window error is popping again here’s my code and also attaching console output image.
import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { NavLink } from 'react-router-dom';
const Products = () => {
const [data, setData] = useState([]);
useEffect(()=>{
getProduct();
},[]);
async function getProduct() {
var res = await axios.get("http://localhost:9900/products");
console.log(res.data);
setData(res.data);
}
return (
<>
<div>
{data.length > 0 && (
data.map((product) => {
return (
<>
<div className="col-md-3 mb-4">
<div className="card h-100 text-center p-4 border-0 " key={product.productId} >
<NavLink to={`/products/${product.productId}`}><img src={product.productImage} className="card-img-top" alt={product.productTitle} height='250px' /></NavLink>
<div className="card-body">
<h5 className="card-title mb-0">{product.productTitle.substring(0, 12)}...</h5>
<h6 className="card-text text-center">Rating {product.productRating}</h6>
<p className="card-text lead fw-bold">${product.productPrice}</p>
<NavLink to={`/products/${product.productId}`} className="btn btn-outline-dark">Buy Now</NavLink>
</div>
</div>
</div>
</>
)
})
)}
</div>
</>
)
}
export default Products
3
Answers
You’re receiving an Object from your API call, so use
res.data.content.map()
or only save thecontent
key, which holds the array you’re looking for:As per your screenshot i can see your data has content element that has all your array data..so instead of
data.map
trydata.content.map
and see if it works for you..First of all your useState will be empty stryng =
" "
.You can try this code…