I’m building a Weather App with React using the free WeatherAPI (weatherapi.com) & useState()
.
When I click the search bar, the page should update with the weather information for the input locale, but this only happens on the second click. See below:
The same thing happens when changing locales from one to another. See below.
I’ve tried the useEffect()
hook instead to update state by setting [locale]
as my dependency array, but I end up with an infinite loop of state updates, reflected by endless logs to the console, so I’d like to try and avoid that outcome for obvious reasons.
Any help is appreciated. Thanks!
import "./weatherCard.css";
import React, { useEffect, useState } from "react";
const WeatherCard = () => {
// state for input
const [input, setInput] = useState("");
// state for locale data
const [locale, setLocale] = useState({});
const [localeName, setLocaleName] = useState("");
const [localeTemp, setLocaleTemp] = useState("");
const [LocaleCondition, setLocaleCondition] = useState("");
const [localeFeelsLike, setLocaleFeelsLike] = useState("");
const [localeWind, setLocaleWind] = useState("");
async function fetchLocaleJSON() {
let localeJSON = { foo: "bar" };
let localeInput = input;
const response = await fetch(
`http://api.weatherapi.com/v1/current.json?key=78a3782df11840c5952223430230105&q=${localeInput}&aqi=no`
);
localeJSON = await response.json();
setLocale(localeJSON);
return console.log(locale);
}
const submitOnEnter = (e) => {
e.preventDefault();
if (e.key === "Enter") {
if (input === "" || input === " ") {
return;
}
document.getElementById("submitSearch").click();
}
};
async function updateWeather() {
if (!input) {
return;
}
await fetchLocaleJSON();
setLocaleName(locale.location.name);
setLocaleTemp(`${locale.current.temp_c}ºC`);
setLocaleCondition(locale.current.conditon);
setLocaleFeelsLike(`Feels like: ${locale.current.feelslike_c}º`);
}
return (
<div id="headerContainer">
<h1>Enter a city</h1>
<h2>or use your ZIP/Postal Code</h2>
<div className="inputContainer">
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
id="inputField"
onKeyUp={submitOnEnter}
/>
<button
id="submitSearch"
onClick={() => {
updateWeather();
}}
>
Search
</button>
</div>
<h2 id="localeName">{localeName ? localeName : ""}</h2>
<h2 id="localeTemp">{localeTemp ? localeTemp : ""}</h2>
<h3 id="localeCondition">{LocaleCondition ? LocaleCondition : ""}</h3>
<h3 id="hiTemp">{localeFeelsLike ? localeFeelsLike : ""}</h3>
{/* <h3 id="localeWind">Wind: 13km/h SE</h3> */}
</div>
);
};
export default WeatherCard;