I'm trying to create a customised homepage for my browser. I have implemented an API to show the weather, but only works when I press enter. I want to display the data automatically when loads the page, without pressing enter, showing the Bristol weather automatically and when I type another location the api will be able to request and render. I tried a lot of ways like (removing the hook, changing the initial state of the hook but nothing seems to work)This is my code:
const [query, setQuery] = useState('Bristol');
const [weather, setWeather] = useState({});
const search = async () => {
fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
.then(res => res.json())
.then(result => {
setWeather(result);
setQuery('')
console.log(result)
});
}
return(
<div className="app">
<main>
<div className="search-box">
<input
type="text"
className="search-bar"
placeholder="Search..."
onChange={e => setQuery(e.target.value)}
value={query}
onKeyPress={search}
/>
</div>
{(typeof weather.main != "undefined") ? (
<div>
<div className="location-box">
<div className="location">{weather.name}</div>
<div className="date">{dateBuilder(new Date())}</div>
</div>
<div className="weather-box">
<div className="temp">
{Math.round(weather.main.temp)}
</div>
<div className="weather">
{weather.weather[0].main}
</div>
</div>
</div>
) : ('')}
</main>
</div>
)
}
I'm new to ReactJS and it's a bit confusing, because here I use the same file to code and to render, I did this before but I was using plain JavaScript with express, etc.. and I rendered into an HTML.