How to check see if the location searched is matched in the api and show an alert to the user if it doesn't match

Viewed 45

At the minute it just shows a fault in the console if you don't search a location in the API(ie Spelling mistake etc..), how do I alert the user when this happens?

     const cityRef = document.querySelector('#location #city');
      
     const searchbar = document.querySelector('.search-bar');
     searchbar.addEventListener('keypress', searchQuery);
     
     function searchQuery(evt) {
      if (evt.keyCode == 13) {
        searchbar.value && getData( searchbar.value );
      }
    }

     function getData(query) {
       fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
       .then(weather => weather.json()).then(displayData);
     };
    

     function displayData(weather) {
       cityRef.innerText = `${weather.name}, ${weather.sys.country}`;}
1 Answers

You can handle error inside catch error block.

Example:

function getData(query) {
  fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
    .then(weather => weather.json()).then(displayData).catch(error => {
      // handle your error
      alert("Your Error Message")
    });
};
Related