I am trying to fetch data using an weather API on a form submission. For the first call, I get no result and then for the subsequent calls I get the result of the previous form input. What could be causing this ? This is how the on submit handler looks :
const [loc, setLoc] = useState("");
const [weather, setWeather] = useState({});
const handleSubmit = (e) => {
e.preventDefault();
console.log(loc);
const url = `http://api.weatherapi.com/v1/current.json?key=${apikey}&q=${loc}&aqi=no`;
fetch(url)
.then((res) => {
return res.json();
})
.then((data) => {
setWeather(data);
console.log(weather);
});
};
This is how the console looks like on making API calls :
Read more here: https://stackoverflow.com/questions/67008143/react-api-calls-use-old-values-of-state-variables
Content Attribution
This content was originally published by Devesh Lohumi at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.