I am writing an application that makes a GET
request through axios to a server I have written. Here is the server code that I have written that may be relevant to the issue.
app.get("/getScheduledTimes/:day/:stationId", (req, res) => {
const {stationId, day} = req.params;
db.collection(`${day}-schedules`).find({
stationInfo: {$exists: true}
}).toArray((error, result) =>{
if(error) {
console.log('Schedule Database Error: ', error)
}
let scheduledTimes;
for(let i = 0; i < result.length; i++){
if(result[i].stationInfo[stationId]){
scheduledTimes = result[i].stationInfo[stationId]
break;
}
}
scheduledTimes = sortTimeArray(scheduledTimes);
res.json({
scheduledTimes: scheduledTimes,
success: true,
})
})
})
What sortTimeArray does is basically sorts the array of objects by date. When I look at what it was sending, res.data.scheduledTimes would be an array of objects, which I expected.
When I make the request from the front end though, originTimeTable
which makes one of the calls returns an array of length 0 with elements in it. However, departTimeTable
returns the array as I expected.
Here is the client-side code:
getTimes = async () => {
// Make API calls to get the timetables for the selected stations
const {originStationId, destinationStationId} = this.state;
const responseOrigin = await axios(`http://localhost:3002/getScheduledTimes/weekday/${originStationId}`)
const originTimeTable = responseOrigin.data.scheduledTimes;
const responseDestination = await axios(`http://localhost:3002/getScheduledTimes/weekday/${destinationStationId}`)
const departTimeTable = responseDestination.data.scheduledTimes;
await this.setState({
originTimes: originTimeTable,
destinationTimes: departTimeTable,
})
}
The result when I console.log originTimetable
is:
originTimetable:
(28) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
length: 0
__proto__: Array(0)
I have read this answer and I understand that originTimetable
array hasn't been resolved. I'm wondering how I can get the elements array to resolve to the array of objects like I expected.
The goal is that I would use originTimeTable
and departTimeTable
to then transform them into one array. Any guidance on how to resolve this issue would be great!