I am trying to build a weather app for a self-guided Vanilla JavaScript course. I have successfully fetched the code for the API from the accuWeather website, but I can’t figure out how to display it. I am trying to make it so that when the user types any letter onto the search bar, it’ll open a drop-down of some sort displaying cities that start with that letter. When I console.log it on the forecast.js file, I am able to get back those cities by applying this method:
data.forEach(city => console.log(`${city.AdministrativeArea.LocalizedName}, ${city.Country.LocalizedName}`))
and setting a random string-letter inside the function getAutoCities().
here is what I have so far:
forecast.js file (Here is where I fetch the information from the API):
const key = 'P7USqIWPhyor91rmlvOTcRaMyMgwfrfrg'
//get Autocomplete List
const getAutoCities = async (search) => {
const base = 'http://dataservice.accuweather.com/locations/v1/cities/autocomplete';
const query = `?apikey=${key}&q=${search}`
const response = await fetch(base + query);
const data = await response.json();
return data;
};
This top part is a separate JS file I made to fetch the API. The bottom one is my app code.
app.js (The code for the app):
const cityForm = document.querySelector('form');
const card = document.querySelector('.card');
const details = document.querySelector('.details');
const time = document.querySelector('.time');
const icon = document.querySelector('.icon img');
const inputField = document.querySelector('input');
const autofill = document.querySelector('.autocomplete')
const updateUI = (data) => {
//destructure properties
const {cityDets, weather} = data;
//update details template
details.innerHTML = `
<h5 class="my-3">${cityDets.EnglishName}</h5>
<div class="my-3">${weather.WeatherText}</div>
<div class="display-4 my-4">
<span>${weather.Temperature.Imperial.Value}</span>
<span>°F</span>
</div>
`;
//update day.night & icon images
const iconSrc = `img/icons/${weather.WeatherIcon}.svg`;
icon.setAttribute('src', iconSrc);
let timeSrc = weather.IsDayTime ? 'img/day.svg' : 'img/night.svg';
time.setAttribute('src', timeSrc);
//remove the d-none if present
if(card.classList.contains('d-none')) {
card.classList.remove('d-none');
}
}
const updateCity = async (city) => {
const cityDets = await getCity(city);
const weather = await getWeather(cityDets.Key);
return {cityDets, weather};
};
cityForm.addEventListener('submit', e => {
e.preventDefault();
//get city value
const city = cityForm.city.value.trim();
cityForm.reset();
//update UI with new city
updateCity(city)
.then(data => updateUI(data))
.catch(err => console.log(err));
});
Where and how would I insert the code to show the data I fetched from the api?