Reputation: 217
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: "",
},
],
},
];
Upvotes: 4
Views: 3038
Reputation: 5054
You can simply do that by checking if every required condition is met and then by looping the modifiers array,
item && item.modifiers && item.modifiers.length && item.modifiers.map((modifier)=> console.log(modifier.cat_name))
Upvotes: 0
Reputation: 13588
You need to ensure your data is an array in the first place. Then you can check whether the array is ready or not.
You should ensure data type is consistent, this is a given.
While waiting for the data to populate (probably from an API call), instead of if-else you can use null propagation operators / optional chaining
Then you can call something like this with a single question mark before the dot.
const newArray = item?.modifier?.map(item => do something)
This way it will suppress the undefined error.
Another step you need to take is conditional rendering.
For example
if (!data?.length) return null
//OR
if (!data?.length) return <div>data is loading</div>
Upvotes: 1
Reputation: 2258
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));
}
}
Upvotes: 4