What will be the easiest way to add an alert statement when the user types a wrong name or number?
let weather = {
fetchWeather: function(city) {
fetch(
"https://api.openweathermap.org/data/2.5/weather?q="
city "&units=metric&appid=fa73f7986fd7a4a71b32273d81cd9fce"
)
.then((response) => response.json())
.then((data) => this.displayWeather(data));
},
displayWeather: function(data) {
const { name } = data;
const { icon , description } = data.weather[0];
const { temp , humidity } = data.main;
const { speed } = data.wind;
document.querySelector(".city").innerHTML = "Weather in " name;
document.querySelector(".icon").src = "https://openweathermap.org/img/wn/" icon ".png";
document.querySelector(".description").innerHTML = description;
document.querySelector(".temp").innerHTML = temp " °C";
document.querySelector(".humidity").innerHTML = "Humidity : " humidity " %";
document.querySelector(".wind").innerHTML = "Wind Speed : " speed " km/h";
},
search: function() {
this.fetchWeather(document.querySelector(".search_bar").value);
}
}
document.querySelector(".search").addEventListener("click", function() {
weather.search();
})
CodePudding user response:
Just check return value of API call. If wrong city return value is:
{"cod":"404","message":"city not found"}
Then modify your code to something like this:
function(city) {
fetch(
"https://api.openweathermap.org/data/2.5/weather?q="
city "&units=metric&appid=xxx"
)
.then((response) => response.json())
.then((data) => {
if(data.cod && data.cod === "404") {
alert("City not found");
} else {
displayWeatherData(data);
}
});
}
Note: dont publish API keys.
CodePudding user response:
You could add an if
statement in your displayWeather
function to create an alert if there is no data :
displayWeather: function(data) {
if (!data) {
alert("Message here");
return;
}
const { name } = data;
[...]