Question:
why is my code able to fetch cordinates but unable to return weather data
Current behavior:
throwing error(could not fetch weather focust)
Desired behavior
return the weather status for now and return weather forecast foe next five days
Repl link:
https://replit.com/@stonecode254/WeatherApp#script.js
code snippet
const searchButton= document.querySelector(".search-btn");
const weatherCardDiv=document.querySelector(".weather-cards");
const cityInput=document.querySelector(".city-input");
const API_KEY="f5c1d0cd4252bf7651dd282d69e21b31";
const createWeatherCard=(weatherItem) =>{
return `<li class="card">
<h3> (${weatherItem.dt_txt.split(" ")[0]})</h3>
<img src="https://openweathermap.org/img/wn/${weatherItem.weather[0].icon}@2x.png" alt="weather-icon">
<h4>Temp:${(weatherItem.main.temp - 273.15).toFixed(2)} °C</h4>
<h4>Wind: ${weatherItem.wind.speed} M/S</h4>
<h4>Humidity:${weatherItem.main.humidity}%</h4>
</li>`;
}
const getWeatherDetails=(cityName, lat, lon) => {
const WEATHER_API_URL = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude=minutely,hourly&appid=${API_KEY}`;
fetch(WEATHER_API_URL).then(res => res.json()).then(data => {
//filter the forecast to get only one forecast per day
const uniqueForecastDays=[];
const fiveDaysForecast=data.list.filter(forecast => {
const forecastDate=new Date(forecast.dt_txt).getDate();
if(!uniqueForecastDays.includes(forecastDate)){
return uniqueForecastDays.push(forecastDate);
}
});
console.log(fiveDaysForecast);
fiveDaysForecast.forEach(weatherItem => {
weatherCardDiv.insertAdjacentHTML("beforeend",createWeatherCard(weatherItem));
});
}).catch(() => {
alert("An error occurred while fetching the Weather forecast");
});
}
const getCityCoordinates= () =>{
const cityName=cityInput.value.trim();
if(!cityName) return;
//console.log(cityName);
const GEOCODING_API_URL = `https://api.openweathermap.org/geo/1.0/direct?q=${cityName}&limit=1&appid=${API_KEY}`;
//Get Coordinates of entered city
fetch(GEOCODING_API_URL).then(res => res.json()).then(data => {
// console.log(data)
if (!data.length) return alert(`No coordinates found for ${cityName}`);
const { name, lat, lon} =data[0];
getWeatherDetails(name, lat, lon);
}).catch(() => {
alert("An error ocurred while fetching the coordinates");
});
}
searchButton.addEventListener("click", getCityCoordinates);