I want to include a simple script in my page that retrieves the weather from an api endpoint and adds it to my page. The error that I get is.
app.js:10 Uncaught TypeError: Cannot read property 'periods' of undefined
at displayWeather (app.js:10)
at app.js:13
displayWeather @ app.js:10
(anonymous) @ app.js:13
After the page loads, I can run the displayWeather() function in the console, and the result is added to the DOM at that point.
I've tried moving all of the code into a single function, same result.
const address = 'https://api.weather.gov/gridpoints/LMK/49,64/forecast';
let weather = $.getJSON(address, function(data) {
weather = data;
});
function displayWeather(){
$(".weather").html("Current Temperature: " +
weather.properties.periods[0].temperature + " F");
$(".weather").append("</br>" +
weather.properties.periods[0].detailedForecast);
};
displayWeather();
This should add the information to the dom on page load, however gives the undefined error. I can run the displayWeather function in the console after page load and it works perfectly.