0

I am getting "cannot read property of undefined" when using map function over array of objects. As this error only happens when am using external api fetch to get data. If i hardcode the array and do the same thing - am getting result.

This is my data:

const ticket= {
  "inventoryId": "2001600236510005688",
  "inventoryItems": [
    {
      "fare": "399.00",
      "passenger": {
        "age": "26",
        "gender": "m",
        "title": "Mr"
      },
      "seatName": "5",
    },
    {
      "fare": "399.00",
      "passenger": {
        "age": "26",
        "title": "Ms",
        "gender": "f",
      },
      "seatName": "6",
    }
  ],
  "serviceCharge": "0.00",
}

So my map function is as follows:

     const ticket_data = [ticket.inventoryItems].flat();
     ticket_data.map((o,i) => 
             (
                <View key={i}>
                 <View style={{ flexDirection: 'row' }}>
                     <View style={{  }}>
                          <Text>Name</Text>
                          <Text>Age</Text>
                          <Text>Gender</Text>
                     </View>
                     <View style={{  }}>
                         <Text>{o.passenger.name}</Text>
                         <Text>{o.passenger.age}</Text>
                         <Text>{o.passenger.gender}</Text>
                      </View>
                 </View>
                                    
                 <View style={{  }}>
                       <Text>Seat: {o.seatName}</Text>
                 </View>
                </View>
             )          
       )

Thus am getting error as "cannot read property 'passenger' of undefined" but when i hard code the data and do the same thing - its showing the output ! How to handle this ? And sometime the inventoryItems will be singular object rather that array so need solution for both

And this is React Native code

samanthas
  • 79
  • 1
  • 7
  • What is `ticket_data`? Is it `data.inventoryItems` or something else? If `ticket_data` is empty intially, how will it throw *"cannot read property 'passenger' of undefined"* error? – adiga Dec 19 '20 at 12:51
  • check now @adiga – samanthas Dec 19 '20 at 12:52
  • Nope, am aware of asynchronous calls ! My data list is long am just showing few data points which make error ! I am able to show other datas in the screen ! The only with problem is the above on my question ( In other words, on the same api call am getting multiple datas, and am using that to display but the one with object am getting problem ) @Ivar – samanthas Dec 19 '20 at 12:55
  • What is the purpose of `[ticket.inventoryItems].flat();`? It is still unclear how you are getting *"cannot read property 'passenger' of undefined"*. – adiga Dec 19 '20 at 12:55
  • can you show the value of `ticket` ? – Sakshi Dec 19 '20 at 12:56
  • As some time the "inventoryItems" will be a single object so am just using flat in order to maintain as array ! @adiga – samanthas Dec 19 '20 at 12:57
  • @samanthas If you put `console.log(JSON.stringify(ticket_data, null, 2))` before your `.map()`, what does it log? – Ivar Dec 19 '20 at 12:58
  • My bad, the variable name of array is ticket - i have changed above do check now ! Hope you understand now @adiga – samanthas Dec 19 '20 at 12:58
  • Kindly do check now, i have updated few things ! name of array const is "ticket" and am using that on the map @adiga – samanthas Dec 19 '20 at 13:01
  • If hardcoding the object works and when receiving the object from an API doesn't work, the problem is either **the object you receive is not the same structure as the hardcoded one, you are not receiving the object correctly or you are trying to process the object before receiving it**. Have you tried to console.log the received object just before flatenning it? Also, try to add some breakpoints and follow your code execution step by step. – Jorge Fuentes González Dec 19 '20 at 13:01
  • First it gives "Null" and then it gives the data @Ivar – samanthas Dec 19 '20 at 13:03
  • @samanthas Do you mean like `[null, {restOfThedata}...`? If so, then that is why it breaks. The first iteration of your `.map()`, `o` is `null` so it cannot read `passenger` from it. You'll need to figure out where that `null` comes from, or if it is correct, build in a check to handle when `o` is `null` (or `undefined`). – Ivar Dec 19 '20 at 13:06
  • @samanthas then you are making a call BEFORE receiving the data, as you are receiving `null`. Read the `How do I return the response from an asynchronous call?` answers because there's something wrong. – Jorge Fuentes González Dec 19 '20 at 13:41
  • You probably have some null data in the array. You can either use `o?.passenger?.name` etc to avoid the error. OR you can `filter` before rendering to remove all the null `ticket_data.filter(t => t).map(...)` – adiga Dec 21 '20 at 07:13

2 Answers2

0

Probably data aren't fetched, while view is rendering. Has ticket_data variable default value set to []?

You can check if inventoryItem is array

Array.isArray(inventoryItems)
  • If `ticket_data` is `[]`,how will it throw *"cannot read property 'passenger' of undefined"* error? The callback will be executed on `0` items – adiga Dec 19 '20 at 12:52
  • mmm... yes, You're right – Maciej Ostojski Dec 19 '20 at 12:54
  • Nope, the datas are fetched ( Am getting other datas in my api - so am sure that the datas are fetched ! ) The problem is with the nested object i believe – samanthas Dec 19 '20 at 12:56
0

enter image description hereI did this:

const ticket_data = ticket.inventoryItems;
  useEffect(() => {
    console.log(ticket_data);
    ticket_data.map((k, v) => {
      console.log(k.passenger.title);
    });
  }, []);

and got the correct output:

Mr
Mrs

Note:Ignore the useEffect part.it has nothing to do with your error. Have added screenshot of the same

Sakshi
  • 1,464
  • 2
  • 8
  • 15