Hi guys Im building a weather app in React and I wanted to set the state variable "city" to the input value so that I can plug it back into the API URL but I had to click twice for the API to display properly. The first click returned "Error: Request failed with status code 400".
This is where I am getting the API from:
const URL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${APIKey}`;
This is my API call:
const getCity = () => {
axios
.get(URL)
.then(function (response) {
setWeatherData(response.data);
})
.catch(function (err) {
console.warn(err);
});
};
This is the function I was having trouble with...
function handleChange() {
const bar = document.getElementById("input-field").value;
if (bar.indexOf(" ") > -1) {
setCity(bar.split(" ").join(" "));
} else {
setCity(bar);
}
}
This is the JSX:
<input
id="input-field"
className="searchbar"
type="text"
placeholder="Name of city (e.g. Austin"
/>
<button
className="searchbtn"
onClick={() => {
handleChange();
getCity();
}}
>
search
</button>
CodePudding user response:
The problem is that city
and therefore URL
are only evaluated at the next render, not immediately.
Remove getCity()
from your onClick
handler and add it in a useEffect()
that depends on city
useEffect(() => {
axios.get("https://api.openweathermap.org/data/2.5/weather", {
params: {
q: city,
appid: APIKey
}
})
.then(({ data }) => setWeatherData(data))
.catch(console.warn)
}, [ city ])