I've made this library app where the user can post a book in their account. When the user post a new Book it's supposed to refresh data, fetching books, including the newest and display them, that works. The problem is that when it does the fetch and display all books again, it duplicates the dom elements instead of overwriting them. Here's the code:
//POST THE NEW BOOK
addBookForm.addEventListener('submit', (e) => {
e.preventDefault()
const title = document.querySelector('#bookTitle').value
const author = document.querySelector('#bookAuthor').value
const pages = document.querySelector('#bookPages').value
const description = document.querySelector('#bookDescription').value
const image = document.querySelector('#bookImage').files[0]
const read = document.querySelector('#bookRead').checked
addBookForm.reset()
addBookModal.hide()
uploadToUserRef(image, title)
.then(image =>{
addNewBook(title, author, pages, description, image, read)
})
.then(fetchBooks)
.then(books => {
books.forEach(book => {
addCardToHTML(book.data().title, book.data().author, book.data().pages, book.data().description, book.data().image, book.data().read)
})
})
})
// DISPLAY BOOKS
function fetchBooks() {
const docRef = db.collection('users').doc(auth.currentUser.uid).collection('books')
return new Promise((resolve, reject) => {
docRef.get().then(querySnapshot => {
resolve(querySnapshot.docs)
}).catch(err => {
console.log(err);
})
})
}
// INJECT THE BOOK CARDS INTO THE HTML
function addCardToHTML(title, author, pages, description, image, read) {
const card = `<div class="card shadow col-sm-12 col-lg-3 m-3" style="max-width: 15rem; min-height: 350px;">
<div class="card-body">
<div class="mb-2" style="background-position: center; background-repeat: no-repeat; background-size: cover; background-image: url(${image}); height: 150px; width: 190px;" ></div>
<h5 class="card-title text-danger">${title}</h5>
<h6 class="card-subtitle mb-2 text-muted">${author} ${pages}</h6>
<p class="card-text">${description}</p>
<span class = ${read == true ? "text-success": "text-danger"}>${read == true ? "I've read this book" : "I haven't read this book yet"}</span>
</div>
</div>`
library.innerHTML += card
}
I've tried to clear the feed before displaying the book cards again, but it just clear the feed and didn't display any card. Thanks!