I am making an app using React Native to show railway PNR status after entering PNR Number using API.
API Results,
Array [
Object {
"data": Object {
"boarding_station": Object {
"day_count": "X",
"departure_time": "XX:XX",
"station_code": "XXX",
"station_name": "XXXXX",
},
"booking_date": "XX/XX/XXXX",
"chart_prepared": X,
"class": "XX",
"date": "XXXX-XX-XX",
~~~~~~~~~~~~~~~~~~~~~~
"passenger": Array [
Object {
"bookingBerthCode": "XX",
"bookingBerthNo": "XX",
"bookingCoachId": "XX",
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
},
],
"pnr_number": "XXXXXXXXXXX",
"quota": "XX",
"train_name": "XXXX",
"train_number": "XXXX",
},
"message": "Success",
"status": true,
"timestamp": XXXXX,
},
]
Code
const [apiResults, setAPIResults] = useState([])
const fetchPNRStatus = async () => {
try {
const response = await fetch(`API Link`, headers)
const results = await response.json()
setAPIResults([results])
console.log(apiResults)
} catch (error) {
console.log(error.message)
}
}
console.log(apiResults) displays the API results as given above. But I want to get specific values like departure_time under boarding_station array or booking_date or
bookingBerthCode under passenger array etc.
How to do that?
Okay, I figured it out. Since, the api response is an array and there is only one object inside the array so all I needed was to use apiResults[0] to access that object.
So, for departure_time it will be apiResults[0].data.boarding_station.departure_time.
Similarly, for booking_date, apiResults[0].data.booking_date.
And, for bookingBerthCode, it is apiResults[0].data.passenger[0].bookingBerthCode.