In this example, we will make a API request to an external server, and populate our UI with the data we received.
For this example we will use Open Weather Map to retrieve real-time weather data for a city.
constappid='fe72...8f37'// Get your app ID from Open Weather Map: https://home.openweathermap.org/api_keyssearch.onChange=triggerUpdate;lettimeout;// We create a debounce function so that API is only requested when the user has finished typing the city namefunctiontriggerUpdate(){if(timeout)clearTimeout(timeout);timeout=setTimeout(getWeatherData,500);}asyncfunctiongetWeatherData(){timeout=0;try{// We will use the asynchrons request.get function to make the request to the APIconst{body}=awaitrequest.get(`https://api.openweathermap.org/data/2.5/weather?q=${search.value}&appid=${appid}&units=Metric`);consttemp=body.main.temp;letwind=body.wind.speed;// Here we update the values of the UI components, with the values we received from the API requesttxt_city.value=body.name;txt_temp.value=`${Math.round(temp)}°`;txt_wind.value=`${Math.round(wind)} Kmh`;// We use the Javascript Date() function to get the current day.constcurrentDate=newDate();txt_day.value=currentDate.toLocaleString('en-US',{weekday:'long'});}catch{// If we did not manage to make the API request, we can handle the error here.console.error("CANNOT CONNECT TO API");}}