Okay I have the following problem:
On a button click, I want to do a GET-Request to retrieve lat/lon data of a address, update the state of the component and then move on to the next page with the updated state as passed data.
My code looks like this:
// useState setup
const [lat, setLat] = useState(0);
const [lon, setLon] = useState(0);
// async function which sets the state
async function geocode (text: string) {
let request = 'https://geocoder.ls.hereapi.com/6.2/geocode.json?' +
'&searchtext=' + text +
'&maxresults=1'+
'&gen=9'+
'&apiKey=xxx';
fetch(request)
.then(res => res.json())
.then((result) => {
console.log("before setting state values:", result.Response.View[0].Result[0].Location.NavigationPosition[0].Latitude, result.Response.View[0].Result[0].Location.NavigationPosition[0].Longitude);
setLat(result.Response.View[0].Result[0].Location.NavigationPosition[0].Latitude);
setLon(result.Response.View[0].Result[0].Location.NavigationPosition[0].Longitude);
return new Promise<void>((resolve) => {
console.log("in promise values:", lat,lon);
setTimeout(resolve, 10);
})
})
}
// btn click function
async function btnClick (e: any) {
e.preventDefault();
if (checkInputs()) {
await geocode(address);
console.log("after promise values",lat,lon);
history.push({
pathname: '/page/ResultMap',
state: {
address: address,
transportTime: transportTime,
transportType: transportType,
lat: lat,
lon: lon
}
}
)}
}
And the console logs me this:
after promise values 0 0
before setting state values: 52.51605 13.37691
in promise values: 0 0
I would honestly expect that history.push() waits until the await geocode(address) resolves to continue the method execution.
Can someone tell me what I am missing?
I solved the issue by using regular Promises, and not async/await.