lundi 29 juin 2020

Else statement not triggered with fetch

Trying to work on a weather app with JavaScript and at some point in my very not organized code, the 'else' statement doesn't get triggered. I have tried with a really condition, and also with console.log but nothing happens in both ways.

Here is the code:

// Select UI Elements
const weatherIcon = document.querySelector(".weather-icon");
const temperatureValue = document.querySelector(".temperature-value p");
const temperatureDescription = document.querySelector(
  ".temperature-description p"
);
const cityLocation = document.querySelector(".location .city");
const countryLocation = document.querySelector(".location .country");
const notification = document.querySelector(".notification p");

// Temperature Variable
const KELVIN = 273;

// API var and key
const key = "16955d729b3c76913ae62114164ca0d7";

// Error

// Load Geolocation detection
window.addEventListener("load", () => {
  let latitude;
  let longitude;

  // Check browser support for geolocation
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((position) => {
      latitude = position.coords.latitude;
      longitude = position.coords.longitude;

      const api = `http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${key}`;

      fetch(api)
        .then((response) => {
          return response.json();
        })
        .then((data) => {
          const tempData = Math.floor(data.main.temp - KELVIN);
          const descriptionData = data.weather[0].main;
          const cityLocationData = data.name;
          const countryLocationData = data.sys.country;
          temperatureValue.innerHTML = `<p>${tempData} °C`;
          temperatureDescription.textContent = descriptionData;
          cityLocation.innerHTML = `<span class="city">${cityLocationData},</span>`;
          countryLocation.innerHTML = `<span class="country">${countryLocationData}</span>`;
        });
    });
  } else {
    notification.style.display = "block";
    notification.textContent = `Something went wrong`;
    // console.log("something went wrong!");
  }
});

I'm using the OpenWeatheMap API to fetch the data.

Aucun commentaire:

Enregistrer un commentaire