jsonopenweathermap

Openweathermap > json / fetch / property is not always available resulting in undefined


I'm trying to get this to work:

(removed app id)

fetch('https://api.openweathermap.org/data/2.5/weather?lat=39.561937&lon=2.936562&appid=XXX&units=metric&lang=de')
        .then(data => data.json())

     .then(data => {
    const description1 = data.weather[0].description;
    const temperature = data.main.temp;
    const feels = data.main.feels_like;
    const wind1 = data.wind.speed;
    const rain = data.rain['1h'] || '0';

    const weatherIcon = document.querySelector('.icon img'); 
    const iconURL = `https://openweathermap.org/img/wn/${data.weather[0].icon}.png`;
    weatherIcon.setAttribute('src', iconURL);

    // Update the weather values on your web page
    document.querySelector('#description1').innerText = description1;
    document.querySelector('#temperature').innerText = (Math.round(temperature));
    document.querySelector('#feels').innerText = (Math.round(feels));
    document.querySelector('#wind1').innerText = (Math.round(wind1 *3.6));
    document.querySelector('#rain').innerText = rain;


  })
  .catch(error => console.log(error));

The const "rain" > data.rain['1h'] is not always available, if it's available the code above works, but if it's not available it results in: "Cannot read properties of undefined (reading '1h')"

I tried to fix it with " || '0'; but that doesn't seem to work...

Basically if there is no rain, it should show 0.

Thank you for your help!


Solution

  • Use the symbol "?" to prevent such errors:

     const rain = data?.rain?.['1h'] || '0';