[Vuejs]-Returning the current precipitation value from an API in Java Script

0👍

You could use fetch to call the API.

Once we have the result we could use Array.map() to create a list of precipitation objects from the hourly precipitation values.

Each precipitation object will look something like:

{ time: '2022-12-16T16:00' precipitation: 0.1 }

We can then add these values to a table for the week using document.createElement etc.

async function getPrecipitation() {
    const url = 'https://api.open-meteo.com/v1/gfs?latitude=53.08&longitude=8.81&hourly=precipitation';
    let result = await fetch(url).then(resp => resp.json());
    let precipitation = result.hourly.time.map((time, idx) => ({ time, precipitation: result.hourly.precipitation[idx]}));
    return precipitation;
}

function showPrecipationInTable(rows) {
    let el = document.getElementById('output');
    for(let row of rows) {
        let rowEl = document.createElement('tr');
        rowEl.innerHTML = `<td>${row.time}</td><td>${row.precipitation}</td>`;
        el.appendChild(rowEl)
    }
}

async function getAndShowPrecipitation() {
    let precipitation = await getPrecipitation();
    showPrecipationInTable(precipitation);
}

getAndShowPrecipitation()
 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

 <table id="output" class="table table-striped">
  <tr>
<th>Time</th>
<th>Precipitation</th>
  </tr>
</table> 

Leave a comment