3

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: "",
      },
    ],
  },
];

AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
json
  • 177
  • 1
  • 9
  • 1
    Does this answer your question? [How to check if an object is an array?](https://stackoverflow.com/questions/4775722/how-to-check-if-an-object-is-an-array) – ggorlen Dec 20 '20 at 04:59
  • Just check if it's undefined, an object that has a `map` property/function, or is an array, depending on your app's needs. I'm not sure what checking against the empty string would help avoid. A piece of data that could be an empty string or could be an array sounds like a pretty brittle situation to be in. – ggorlen Dec 20 '20 at 05:00

3 Answers3

3

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));
    }
}
Yair Cohen
  • 2,032
  • 7
  • 13
1

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>
Someone Special
  • 12,479
  • 7
  • 45
  • 76
0

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))
Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30