I'm buggered by this bug in a test app that I'm working on. I'll post the full code soon but wasn't sure if anybody had any ideas off hand...
So I've got a Node / Express / React app for doing a restaurant search based on location using Google's Places Search in the Maps API. I'm using the Node server-side Google library for the maps API...
It works but it always takes two hits to the API before displaying the correct results results. No errors or anything, just it always takes two requests to my API endpoint.
Let's say I do a search for Manhattan either using Postman or on the app itself... The first hit to the api
always returns just an empty array [ ]. Then, clicking it again will return the results.
Then let's say I change the search to be Boston, it will
always display the results from Manhattan, and then clicking it again will return the results for Boston.
I thought "Well maybe it's the Google maps API..." but I'm also using a separate endpoint to do Address -> Long/Lat geocoding, and it's the same thing. First hit of the API returns an empty array, [ ], second hit will give me my results. And then if I change it up to another address, first hit will show me the same results from my first search (as if I searched Boston again), second hit will show me the results from the right search.
Here's my server code for just the Address lookup. The function for getting the restaurants data is basically identical by design, just a different api endpoint and Google Maps client function.
Code:
var addressData;
function getAddress(location) {
googleMapsClient.geocode({
address: location
}, function(err, response) {
if (!err) {
console.log('New lookup for ' + location)
addressData = response.json.results;
} else {
console.log(err);
}
});
return addressData
}
// Lookup Address data
app.get('/api/v1/address', function(req, res) {
res.send(getAddress(req.query.location));
})
This is an MVP so it's rough code, but the basic gist of it is that I'm defining a route in express at /api/v1/address. My app (or postman) hits that route using GET, and then express fires my getAddress(); function... Which is defined above. The route passes in the address using the ?location=AddressHere URL query param.
The googleMapsClient.geocode() function is pretty much straight from Google's tests... I just added the error handling and the console.log.
Any thoughts? I'm kinda stumped on it.