Home > Enterprise >  How to fetch data from api and show it in a table?
How to fetch data from api and show it in a table?

Time:08-30

I'm trying to make a covid tracker website but I can't display fetched data in a table format, can you guys please help me to display the data in a table. help me to complete the code

const getdata = async (abc) => {

    const endpoint = 'https://api.covid19api.com/summary'

    const response = await fetch(endpoint)
    const { Countries } = await response.json()
    console.log(Countries)


    Countries.map(({Country}) => {
        console.log(Country)


        // const { Country, NewConfirmed, TotalConfirmed, NewDeaths, TotalDeaths, NewRecovered, TotalRecovered } = Countries






    })

}

getdata().then
<div >

        <table >
            <thead>
              <tr>
                <th scope="col">Country</th>
                <th scope="col">NewConfirmed</th>
                <th scope="col">TotalConfirmed</th>
                <th scope="col">NewDeaths</th>
                <th scope="col">TotalDeaths</th>
                <th scope="col">NewRecovered</th>
                <th scope="col">TotalRecovered</th>
              </tr>
            </thead>



            <tbody id ="tbody">
              <!-- <tr >
                <td>Mark</td>
                <td>Otto</td>
                <td>@mdo</td>
                <td>Mark</td>
                <td>Otto</td>
                <td>@mdo</td>
                <td>@mdo</td>
              </tr> -->
            </tbody>
          </table>




        </div>

I'm trying to make a covid tracker website but I can't display fetched data in a table format, can you guys please help me to display the data in a table. help me to complete the code

CodePudding user response:

You can achieve that this way

const tbody = document.querySelector('#tbody');

const getdata = async () => {
  const endpoint = "https://api.covid19api.com/summary",
        response = await fetch(endpoint),
        data = await response.json(),
        Countries = data.Countries;

 Countries.forEach(countryObj => {
    let {Country, NewConfirmed, TotalConfirmed, NewDeaths, TotalDeaths, NewRecovered, TotalRecovered} = countryObj;
    tbody.innerHTML  = `<tr>
        <td>${Country}</td>
        <td>${NewConfirmed}</td>
        <td>${TotalConfirmed}</td>
        <td>${NewDeaths}</td>
        <td>${TotalDeaths}</td>
        <td>${NewRecovered}</td>
        <td>${TotalRecovered}</td>
    </tr>`;
 });

}
getdata();
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.1/css/bootstrap.min.css" integrity="sha512-Ez0cGzNzHR1tYAv56860NLspgUGuQw16GiOOp/I2LuTmpSK9xDXlgJz3XN4cnpXWDmkNBKXR/VDMTCnAaEooxA==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<table >
  <thead>
    <tr>
      <th scope="col">Country</th>
      <th scope="col">NewConfirmed</th>
      <th scope="col">TotalConfirmed</th>
      <th scope="col">NewDeaths</th>
      <th scope="col">TotalDeaths</th>
      <th scope="col">NewRecovered</th>
      <th scope="col">TotalRecovered</th>
    </tr>
  </thead>
  <tbody id="tbody">
  </tbody>
</table>

CodePudding user response:

Maybe do it programmatically by getting the data and building the headings and rows from that instead of initially hard-coding the HTML markup. This example uses a series of functions to create headings, rows, and cells from the dataset to gradually build up a table from template strings.

// Get the data
const getdata = async(abc) => {
  const endpoint = 'https://api.covid19api.com/summary';
  const response = await fetch(endpoint);
  const { Countries } = await response.json();
  return Countries;
}

// Accepts the first object from the data and
// returns a string of HTML from its keys
function buildHeadings(obj) {
  const keys = Object.keys(obj);
  return keys.map(key => `<th>${key}</th>`).join('');
}

// Accepts a value data and
// returns an HTML table cell
function buildCell(cell) {
  return `<td>${cell}</td>`;
}

// Accepts an object and
// returns a string of row HTML by mapping
// over the object values and, for each, calling
// `buildCell`
function buildRow(obj) {
  const values = Object.values(obj);
  return `<tr>${values.map(buildCell).join('')}</tr>`;
}

// Accepts the data and
// returns a string of row HTML calling
// `buildRow` for each object in the dataset
function buildRows(data) {
  return data.map(buildRow).join('');  
}

// `buildTable` puts it all together and returns
// the final table markup as an HTML string
function buildTable(data) {
  return `
    <table>
      <thead>${buildHeadings(data[0])}</thead>
      <tbody>${buildRows(data)}</tbody>
    </table>
  `;
}

// Returns only the data for each object
// that is required for the table
function getSubset(data) {
  return data.map(obj => {
  
    const {
      ID,
      CountryCode,
      Slug,
      Date,
      Premium,
      ...rest
    } = obj;

    return { ...rest };
  
  });
}

// Cache the container
const container = document.querySelector('.container');

// Get a subset of the returned data, and build the table
// adding the HTML string returned from `buildTable` to the
// container's innerHTML
async function main() {
  const data = getSubset(await getdata());
  const table = buildTable(data);
  container.innerHTML = table;
}

main();
table { border-collapse: collapse; }
thead { text-align: left; }
thead { background-color: lightgreen; }
th, td { padding: 0.25em 0.4em; border: 1px solid #dfdfdf; }
tr:nth-child(even) { background-color: #efefef; }
<div ></div>

Additional documentation

CodePudding user response:

Loop through all the data gathered using the forEach() method and use innerHTML to directly place code to your html file.

  • Related