React : api calls use old values of state variables

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) => {
const url = `${apikey}&q=${loc}&aqi=no`;
  .then((res) => {
    return res.json();
  .then((data) => {

This is how the console looks like on making API calls :

enter image description here

Read more here:

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.

%d bloggers like this: