joeldueckdotcom

Artifact 125c295a3ef0f74b6209d711645e822ac01e2fe56bcec7f8a1b00bca3ccf71b6:


let weatherDiv = document.getElementById('weather');

function updateWeather(tempF, conditions) {
    let tempHue = 210 - (tempF * 2);
    if(tempHue < 0) tempHue = 360 - tempHue;
    document.documentElement.style.setProperty('--base-temp', tempHue);
    weatherDiv.innerHTML = `Robbinsdale, MN: ${tempF}º F; ${conditions}`;
}

function getWeather() {
    weatherDiv.innerHTML = 'Getting weather…';

    let weatherCache = JSON.parse(localStorage.getItem('weather'));

    if(weatherCache === null || Date.now() - weatherCache.timestamp > 3600000) {
        console.log('Weather cache miss; refreshing...');
        fetch('https://api.weather.gov/gridpoints/MPX/105,74/forecast/hourly?units=us')
        .then(function(response) {
            if(!response.ok) {
                throw Error(response.statusText);
            }
            return response.json();
        }).then(function(weatherJson) {
            let weather = weatherJson.properties.periods[0];
            updateWeather(weather.temperature, weather.shortForecast);
            localStorage.setItem('weather',
                JSON.stringify({ "timestamp" : Date.now(),
                  "temp" : weather.temperature,
                  "conditions" : weather.shortForecast }));
        }).catch(function(error) {
            console.log(error);
        });
    } else {
        console.log('Using cached weather data...');
        updateWeather(weatherCache.temp, weatherCache.conditions);
    }
}

getWeather();