Search code examples
javascripthtmljqueryapi-design

API Values for Weather App - Uncaught Type Error


I feel like this is a stupid question but I'm trying to learn more about using APIs with Javascript. I'm using the Open Weather app for the API.

One part of my project will allow the user to type a city into a form, and then the API gets the current weather/current temperature etc. This part works totally fine.

I'm trying to make a page that allows the user to type a city into a form, and then show the forecast for the next few days.

It's not recognizing the values in the API. I believe I'm using the correct documentation on the website, here it is: https://openweathermap.org/forecast16

I'm using fetch and it's getting called, but the values are 'undefined' I get Uncaught TypeError: Cannot read property 'temp' of undefined.

Here's the url and part of the js code:

const api = `https://api.openweathermap.org/data/2.5/forecast/daily? 
q=${input}&cnt=2&lang=en&appid=${myKey}&units=metric`;


  populateUI(data) {

    this.uiContainer.innerHTML = `
    
    <div class="card mx-auto mt-5" style="width: 18rem;">
    <div class="card-body justify-content-center">
    <h5 class="card-title">${data.name}</h5>
    <p class="card-subtitle mb-2 text-muted">Highs of ${data.list.temp.min}. Lows of 
    ${data.list.temp.max}</p>
    <p class="card-text ">Weather conditions are described as: 
    ${data.list.weather.description}</p>
    <p class="card-text ">Feels like: ${data.list.feels_like}</p>

    <p class="card-text ">Wind speed: ${data.list.humidity} m/s</p>          
    </div>
</div>
`;
 }

If I put ${data.list} for all of them instead, I get 401 (Unauthorized) so I'm not sure if my url is wrong, but it looks ok due to the documentation? Do I need to generate a second API key for the forecast, since I already have an API key for the current weather part of the site?


Solution

  • According to the sample JSON structure on the documentation, list is an array of objects, each of which contains properties such as temp. (See https://openweathermap.org/forecast16#JSON)

    To access such properties in your code, you should loop through the items in data.list and get properties from each item. For example:

    let stringAsHTML = ``;
    
    data.list.forEach(obj => stringAsHTML += `<p>Highs of ${obj.temp.min}</p>`);