Okay, I have been struggling with this for hours but I still can’t figure this out so if anyone has the solution, thank you!!!
In my code below, I am fetching data from my API (which then fetches data from the Google Places API Nearby Search. Now the API returns a list of about 20 different locations. For each location, I’ve created an object containing the data only I want. Then, I simply push this data to the business array.
(The fetch is in a loop because the Google API only allows you to search for one type of building (cinema, bookstore, bowling_alley, etc…) at a time so I’ve put the fetch in a loop to loop over all of the different types of buildings I want data of)
Now, my issue is that if I try to get the first business of the businesses array businesses[0], it returns undefined. However, what I find even stranger is if I log the businesses array to the console, it displays all the of the business. I have no idea why this is happening so if anyone knows, please do tell and I’ll be very grateful.
getNearbyPlaces = (latitude, longitude, radius, types) => {
const businesses = [];
types.forEach(async (type) => {
await fetch(`${url}/google/places/nearbysearch?lat=${latitude}&lng=${longitude}&rad=${radius}&type=${type}`, {
method: 'GET',
body: null
}).then(response => {
if (response.ok) {
return response.json();
}
throw new Error('ERROR: Google-Api Nearby Places - response not okay');
}, networkError => console.log(networkError.message)
).then(jsonResponse => {
if (jsonResponse.results) {
jsonResponse.results.forEach(result => (
[...businesses].push({
id: result.place_id,
name: result.name,
address: result.vicinity,
categories: result.types,
rating: result.rating,
reviewCount: result.user_ratings_total
})
))
}
});
});
console.log(businesses); // logs the list of bsuiness
console.log(businesses[0]); // logs undefined
}
Below is the image displayed to the console for when I log the businesses array and businesses[0] (Data has been blocked out for privacy reasons)