I have an array of products, some products may have an array of product colors, but it's not guaranteed. I am trying to map over every color of each product (if available) to give it it's own div. The piece of code I wrote works except for the product.product_colors.map()
part. Any contribution or linking to resources would help. Thanks
Fetched data from api looks like this:
{
"status": 200,
"count": 2,
"data": [
{
"product_id": 1,
"product_name": "PRODUCT NUMBER 1",
"product_price": "14.95",
"product_colors": [
{
"color_id": 1,
"color_name": "Velvet",
"color_description": "A reddish-purple color"
},
{
"color_id": 2,
"color_name": "Navy",
"color_description": "A darkish blue color somewhat similar to the deep ocean color."
}
]
},
{
"product_id": 2,
"product_name": "PRODUCT NUMBER 2",
"product_price": "8.99"
}
]
}
My current code looks like this:
return(
<div>
{data.map((product, index) => (
<div key={index}>
<h2>{product.product_id} ---- {product.product_name}</h2>
<h2>{product.product_price}</h2>
{product.product_colors
?<div><p>No colors available</p></div>
: product.product_colors.map((color) => (
<div>
<p>{color.color_name}</p>
<p>{color.color_description}</p>
</div>
))
}
<br />
</div>
))}
</div>
);
CodePudding user response:
You've switched the conditions. You want to map over the array when product.product_colors
is truthy, which is the first condition.
in other words, you want
product.product_colors ? product.product_colors.map((color) => (
<div>
<p>{color.color_name}</p>
<p>{color.color_description}</p>
</div> : <div><p>No colors available</p></div>
CodePudding user response:
Error is due to the second item not having a product_colors
property. You need to use optional chanining operator (?.
) to get rid of error you get.
product.product_colors?.map((color) => (
<div>
<p>{color.color_name}</p>
<p>{color.color_description}</p>
</div>
))
CodePudding user response:
You need to ensure product.product_colors
exists.
The shortest way to do so is using the optional chaining ?.
syntax:
product.product_colors?.map((color, index) =>
Small example:
const data = {"status": 200, "count": 2, "data": [{"product_id": 1, "product_name": "PRODUCT NUMBER 1", "product_price": "14.95", "product_colors": [{"color_id": 1, "color_name": "Velvet", "color_description": "A reddish-purple color"}, {"color_id": 2, "color_name": "Navy", "color_description": "A darkish blue color somewhat similar to the deep ocean color."} ] }, {"product_id": 2, "product_name": "PRODUCT NUMBER 2", "product_price": "8.99"} ] };
const res = data.data.map((product, index) => {
product.product_colors?.map((color, index) => {
console.log(color);
});
});