I am new to react and I am passing an item prop. Some of the items has an empty array in items.modifiers. When I use an if an if condition i still get an error that "Cannot read property 'map' of undefined " Below is my code. Any help would be really appreciated.
const NewModal = ({ item }) => {
if (item.modifiers !== "") {
item.modifiers.map((modifier) => console.log(modifier.cat_name));
}
};
return [
{
items: [
{
item_id: 1,
item_name: "Philadelphia Steak Sandwich",
modifiers: {
cat_name: " Choose a side",
mod_items: [
{ mod_item_name: "French Fries", price: 1 },
{ mod_item_name: "Cole Slaw", price: 2 },
],
},
},
{
item_id: 2,
item_name: "Philadelphia Steak Sandwich Deluxe",
modifiers: "",
},
],
},
];
Use Array.isArray() first to check whether the item you're trying to map is of type Array.
const NewModal = ({item}) => {
if(Array.isArray(item.modifiers) {
item.modifiers.map((modifier)=> console.log(modifier.cat_name));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With