I'm working on a react native weather app project. I am using openWeatherMapAPI and opencagedata for geolocation. First, Im calling the getGeo()
function that takes in the city and stores the lat and lon from the API. Next, to get the actual weather data, I am calling the getWeatherData()
function that makes the request to the API that uses the lat and lon for the location and stores the JSON data in the weatherData
useState()
.
This all seems like it should work, but it does not. I have the functions run once a button is pressed getGeo() --> getWeatherData()
, but I end up needing to press the button 3 times to get any data to be saved to the weatherData
.
CODE:
function getGeo(){
fetch(`https://api.opencagedata.com/geocode/v1/json?q=${city}&key=${geoApi}`)
.then((response) => response.json())
.then((data) => {
setGeoData(JSON.stringify(data));
setLat(data.results[0].geometry.lat)
setLon(data.results[0].geometry.lng)
})
.catch((error) => {
// Handle any errors that occur
alert(error);
});
}
function getWeatherData() {
fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude=minutely&appid=${weatherApi}&units=metric`)
.then((response) => response.json())
.then((data) => {
setWeatherData(JSON.parse(JSON.stringify(data)));
})
.catch((error) => {
// Handle any errors that occur
alert(error);
});
console.log(weatherData)
setShowData(true);
}
function onPress() {
// hide the keyboard
Keyboard.dismiss();
// get the lat and lon
getGeo();
// get the weather data
getWeatherData()
}
To fix my problem, I tried to use async and await
functions thinking the code was moving on before the weather API could respond to the request. when I did this I didn't solve my problem the same result happened as before. (Needing to press the button 3 times for data to be entered into the weatherData useState
)
I have also tried to use promises while trying to get the response from the API call with no different result.
this is the output I get to the console while pressing the button
LOG undefined
LOG {"cod": "400", "message": "Nothing to geocode"}
LOG {"current": {"clouds": 35......
is there anything else I can try to fix this issue?