//OpenWeather Info
const weatherKey = '*********';
const weatherURL = 'https://api.openweathermap.org/data/2.5/weather'
//Page Elements
const input = document.querySelector("#input").value;
const button = document.querySelector('#submit');
//Fetch
const getWeather = async () => {
try {
const apiURL = weatherURL+ "?&q=" + input + "&APPID=" + weatherKey;
console.log(apiURL);
const response = await fetch(apiURL);
if (response.ok) {
const jsonResponse = await response.json();
console.log(jsonResponse);
return jsonResponse;
} else {
console.log("request failed!");
}
} catch (error) {
console.log(error);
}
**}**
const renderWeather = (data) => {
document.querySelector("#weather-degrees").innerHTML = data.main.temp;
}
const executeSearch = () => {
getWeather().then(data => renderWeather(data));
}
button.addEventListener('click', executeSearch());
I can't get the value of input when I type in the textbox and it won't fetch the apiURL. Before I even type in anything the console gives me this. Any help? console logs
Your input
is set once beforehand. Instead, do something like:
const input = document.querySelector("#input");
// ...
const apiURL = weatherURL+ "?&q=" + input.value + "&APPID=" + weatherKey;
// or using a template literal
const apiURL = `${weatherURL}?&q=${input.value}&APPID=${weatherKey}`;
Mind that you should also URL encode the input.
Since input
is only set once now, it's set to an empty string. You can directly visit the API url, i.e. https://api.openweathermap.org/data/2.5/weather?APPID=82510feaa0c1d3a300a7a754ff134404&q= and notice that it doesn't work. If you replace q=
with a proper value, e.g. q=London
, it will work fine.
Mind that the API will also return a 400 error (but with a different error message) if you pass it an invalid city. Read the error from the reponse body and properly display an error to the user about invalid input.