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