Petromir Kolev
Petromir Kolev

Reputation: 37

Dynamically adding an HTML section via JavaScript duplicates the HTML code on refresh

I am trying to resolve a course project of mine and I am having hard time with one of the functionalities. I have a piece that should fetch and display all entries from a Firebase DB but what it does on refresh is to add one more to the DOM (no change in Firebase) instead of simply returning the Firebase results.

const data = {
  "-MQufI6df_3HJ6WQtB0u": {
    "author": "Test",
    "isbn": "123",
    "title": "Testing1"
  },
  "-MQufLMu5gGKQlZE0UrN": {
    "author": "Test",
    "isbn": "123",
    "title": "Testing2"
  },
  "-MQufLwiyLP6T3pXHKH5": {
    "author": "Test",
    "isbn": "123",
    "title": "Testing3"
  }
}


document.getElementById('loadBooks').addEventListener('click', function() {
  document.getElementById('booksList').innerHTML = '';

  let books = Object.entries(data);

  for (const book in books) {
    console.log(book);

    let currentBook = books[book][1];
    let newBook = document.createElement('tr');
    newBook.innerHTML = `
                <tr>
                 <td>${currentBook.title}</td>
                 <td>${currentBook.author}</td>
                 <td>${currentBook.isbn}</td>
                 <td style="display: none">${books[book][0]}</td>
                 <td>
                  <button>Edit</button>
                  <button>Delete</button>
                 </td>
                </tr>
                    `;
    document.getElementById('booksList').appendChild(newBook);
  }
});
<button id="loadBooks">LOAD ALL BOOKS</button>
<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Author</th>
      <th>Isbn</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody id="booksList">
  </tbody>
</table>

<form>
  <h3>FORM</h3>
  <label>TITLE</label>
  <input type="title" id="title" placeholder="Title...">
  <label>AUTHOR</label>
  <input type="title" id="author" placeholder="Author...">
  <label>ISBN</label>
  <input type="title" id="isbn" placeholder="Isnb...">
  <button id="submit">Submit</button>
</form>

Current result: Lets say I have 1 book: Book - John Smith - 1234

After hitting again the 'loadBooks;' btn I see in the browser: Book - John Smith - 1234 Book - John Smith - 1234

Expected result: On refresh I should only see: Book - John Smith - 1234

until I add a second book to my list.

Upvotes: 1

Views: 66

Answers (1)

Sanoodia
Sanoodia

Reputation: 915

you need to simply add one check before appending child 'newBook' in 'booksList'

var booksList = document.getElementById("booksList");
if(booksList !== null){ // thats means its exists in dom
   document.getElementById('booksList).innerHTML = ''
}

Upvotes: 1

Related Questions