I have a problem with my weatherApp, the first API is working and I’m getting all of the data, but I also want to include air pollution but this isn’t working, I have the coordinates its asking for but the response I get is nothing to geocode. Anyone knows what I’m doing wrong?
function Forecasts() {
const [data, setData] = useState({});
const [city, setCity] = useState("");
const [lat, setLat] = useState("");
const [lon, setLon] = useState("");
const [pollution, setPollution] = useState({});
const apiKey = import.meta.env.VITE_API_KEY;
const searchLocation = () => {
// Fetch weather data
const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;
axios.get(weatherUrl)
.then((response) => {
setData(response.data);
setLat(response.data.coord.lat);
setLon(response.data.coord.lon);
console.log(response.data);
console.log(response.data.coord.lat);
console.log(response.data.coord.lon);
// Fetch pollution data using coordinates
const pollutionUrl = `https://api.openweathermap.org/data/2.5/air_pollution?lat=${lat}&lon=${lon}&appid=${apiKey}`;
axios.get(pollutionUrl)
.then((pollutionResponse) => {
setPollution(pollutionResponse.data);
console.log(pollutionResponse.data);
})
.catch((pollutionError) => {
console.error("Error fetching pollution data:", pollutionError);
});
})
.catch((error) => {
console.error("Error fetching weather data:", error);
});
setCity("");
}
I’m clueless at this point.
2
Answers
Thе issuе you arе facing is rеlatеd to thе timing of thе
lat
andlon
variablеs you arе trying to usе thеlat
andlon
valuеs to construct thе URL for fеtching air pollution data immеdiatеly aftеr callingsеtLat
andsеtLon
thе statе updatеs arе asynchronous so thе valuеs oflat
andlon
may not havе bееn updatеd yеt whеn you usе thеm to construct thе pollutionUrl this is why you arе gеtting thе "nothing to gеocodе" еrrorSetting state in react js is asynchronous. You are using setLat() and setLon(), which are asynchronous here. At the time of second api call both the states are empty. Instead try below: