0

I am trying to retrieve datas from an api by triggering a button.but evertimes i click the button the old datas remain exist which i dont want.i want the table will be reloaded and will have new datas from api.

    const showData = document.querySelector('.showData')
    const btn = document.querySelector('.shwData-btn')


    btn.addEventListener('click', showdata)


    function showdata(){

    fetch('http://localhost:5000/posts')
    .then(res => res.json())
    .then(data=>{
        data.forEach(item =>{
            const id = item['_id']
            const name = item.name
            const email = item.email
            const age = item.age

            const tr = document.createElement('tr')

            tr.innerHTML = `

                <tr>
            <td>${id}</td>
            <td>${name}</td>
            <td>${email}</td>
            <td>${age}</td> 
            </tr>
            `

            showData.appendChild(tr)

    })})}


<!-- language: lang-html -->

    <button class="shwData-btn">Showdata</button>
            <table class="showData">
                <tr>
                    <td>id</td>
                    <td>email</td>
                    <td>name</td>
                    <td>age</td>
                </tr>

            </table>
JsStudent
  • 99
  • 1
  • 1
  • 6

1 Answers1

0

You will have to render a blank table or clear all rows(tr) before populating it with data.

const showData = document.querySelector('.showData')
    const btn = document.querySelector('.shwData-btn')


    btn.addEventListener('click', showdata)


    function showdata(){

    fetch('http://localhost:5000/posts')
    .then(res => res.json())
    .then(data=>{
// Clear your table here or populate with blank data
// tbody because you do not want to clear column heading. Make sure you have tbody and theader
$(".showData tbody tr").remove();

        data.forEach(item =>{
            const id = item['_id']
            const name = item.name
            const email = item.email
            const age = item.age

            const tr = document.createElement('tr')

            tr.innerHTML = `

                <tr>
            <td>${id}</td>
            <td>${name}</td>
            <td>${email}</td>
            <td>${age}</td> 
            </tr>
            `

            showData.appendChild(tr)

    })})}


<!-- language: lang-html -->

    <button class="shwData-btn">Showdata</button>
            <table class="showData">
                <tr>
                    <td>id</td>
                    <td>email</td>
                    <td>name</td>
                    <td>age</td>
                </tr>

            </table>

Highly recommend to have a look at this as well: Delete all rows in an HTML table

LearningEveryday
  • 584
  • 1
  • 3
  • 13