Reputation: 5073
I am trying to send the latitude and longitude of an address to a Firebase database. Weirdly, the value does get logged out, but won't be sent to the database.
I am using the React Geocode library to get the longitude and latitude. It works (they do get logged to the console), but apparently it takes sometime for it to work, since it is not the values sent to the database.
I did some research and think it might be because I don't have an async function somewhere in there. Could this really be the problem?
onSubmit={(values, { setSubmitting }) => {
values.address = `${values.street}, ${values.num}, ${values.neighbourhood}, ${values.city}`
Geocode.fromAddress(values.address).then(
response => {
const { lat, lng } = response.results[0].geometry.location;
values.latitude = lat.toString() //why doesn't this work?
values.longitude = lng.toString() //why doesn't this work?
console.log(values.latitude) //this will log on the console
//but won't go to the database
},
error => {
console.error(error);
}
);
const { name, latitude, longitude, rating, address } = values
const valuesToSend = { name, latitude, longitude, rating, address }
async function writeToFirebase() {
await firestore.collection('businessesPendingAdminApproval').add(valuesToSend)
}
writeToFirebase()
}}>
Upvotes: 2
Views: 140
Reputation: 31595
The reason why that doesn't work is because you modify the values inside the .then
of Geocode.fromAddress
, which is an async call. And because you don't use await
on the call, the code just pass by that and go directly to the firebase call.
What you need to do is add await
before Geocode.fromAddress
.
await Geocode.fromAddress(values.address).then(...)
Upvotes: 1