I’m getting an error called "Uncaught TypeError: product.color?.map is not a function" i’m getting this error when i try to map the color of product is single product page
<Filter>
<FilterTitle>Color</FilterTitle>
{product.color?.map((c)=>(
<FilterColor color={c} key={c} />
))}
</Filter>
I fetching product data form here
const Product = () => {
const location = useLocation();
const id = location.pathname.split("/")[2];
const [product, setProduct] = useState({});
useEffect(() => {
const getProduct = async () => {
try {
const res = await publicRequest.get("/products/find/" + id);
setProduct(res.data.product);
// console.log(res);
} catch(error) {
console.log(error);
}
};
getProduct();
}, [id]);
2
Answers
The effect is going to be called after the component is initially rendered, therefore in the first render, the
product.color
is undefined. And it seems thatcolor
is a string, not an array therefore you do not need to usemap
, just display the result.You can put a conditional to only render when you get the result from the API:
Based on the data you provided, a product.color is a single object so, you can’t use the map in a single object.
If you want to map then you have to map the product which has multiple objects