Search code examples
javascriptarrayslocal-storagedom-eventsdomcontentloaded

How to display the content of my Local Storage using DOMContentLoaded with JavaScript


I'm working on a Library App and I need to display the content of my Local Storage on the main page. I know how to get the array of books but I'm having hard time trying to show it on the page inside a table.

The table is created inside another function when the user clicks a submit button on a form (addBookToList()).

Is there a way I can reuse the same function and display the books from the Local Storage on the same table when the user reload the page?

HTML:

    <form action="#" class="form">
        <label for="title">Title</label>
        <input type="text" id="title" required>
        <label for="author">Author</label>
        <input type="text" id="author" required>
        <label for="num-pages">No. of pages</label>
        <input type="number" id="num-pages" required>
        <br>
        <span>Have you read this book?</span>
        <br>
        <input type="radio" name="radio" id="yes" value="yes" checked>
        <label for="yes" class="yes">Yes</label>
        <input type="radio" name="radio" id="no" value="no">
        <label for="no" class="no">No</label>
        <div class="button-div">
            <button id="add-btn" type="submit">SUBMIT</button>
        </div>
    </form>
</div>

<div class="table-box">
    <hr>
    <table>
        <thead>
            <tr>
                <th>Title</th>
                <th>Author</th>
                <th>No. of pages</th>
                <th>Read</th>
            </tr>
        </thead>
        <tbody class="list"></tbody>

    </table>
</div>

JAVASCRIPT:

// Get values
let formContainer = document.querySelector('.form-div');
let form = document.querySelector('.form');
let addBtn = document.querySelector('#add-btn');
let btnNewBook = document.querySelector('#addBook-btn');

// Book constructor
function Book(author, title, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}

// Empty array to store books
let myLibrary = [];

// Form event listener
form.addEventListener('submit', (e) => {
e.preventDefault();

  // Hide form and show home page
  document.querySelector('.table-box').style.display = 'block';
  document.querySelector('.para-div').style.display = 'block';
  form.style.display = 'none';

  // Get values from User
  let title = document.querySelector('#title').value;
  let author = document.querySelector('#author').value;
  let pages = document.querySelector('#num-pages').value;
  let read = getRead();

  // Instantiate book
  const book = new Book(author, title, pages, read);

  // Push book to the library, show it on the UI and clear the form
  myLibrary.push(book);

  addBookToList();

  // Add book to Local Storage
  addBook();

  // Show success alert
  showAlert('Book added!', 'success');

  // Clear form
  form.reset();

});

// Add book to list
function addBookToList() {
  const list = document.querySelector('.list');

  // Create new row element
  const row = document.createElement('tr');

  // Loop through myLibrary array
  myLibrary.forEach(value => {

    // Add the book to the table
        row.innerHTML = `
        <td>${value.title}</td>
        <td>${value.author}</td>
        <td>${value.pages}</td>
        <td>${value.read}</td>
        <td><a href="#" class="btn delete">X</a></td>`;
});

// Append the row to list
list.appendChild(row);
}

// Storage
function getLibrary() {
   if(localStorage.getItem('myLibrary') === null) {
     myLibrary = [];
   } else {
     myLibrary = JSON.parse(localStorage.getItem('myLibrary'));
   }
   return myLibrary;
 }

 function addBook() {
   localStorage.setItem('myLibrary', JSON.stringify(myLibrary));
 }

 function removeBook(index) {
   getLibrary();
   let removed = myLibrary.indexOf(index);
   myLibrary.splice(removed, 1);
   localStorage.setItem('myLibrary', JSON.stringify(myLibrary));
 }

 // Load page event listener
 document.addEventListener('DOMContentLoaded', function displayBooks(){

   getLibrary();
   addBookToList();

 });

Solution

  • I will say that I don't like your coding style at all... but here is a simple solution that is not optimal in my opinion.

    document.addEventListener('DOMContentLoaded', ()=>{
      const list = document.querySelector('.list'); // why get it again
      getLibrary();
      let row;
      for(let b of myLibrary){ // I like this kind of loop since you can break out of it if needed
        row = document.createElement('tr'); // new instance at each step of loop
        row.innerHTML = `<td>${b.title}</td>
          <td>${b.author}</td>
          <td>${b.pages}</td>
          <td>${b.read}</td>
          <td><a href="#" class="btn delete">X</a></td>`;
        }
        list.appendChild(row);
      }
    });