Search code examples
javascriptlocal-storagejavascript-objects

Cannot save object to localstorage


I am building a bookcase to store information about books that someone is reading. I want to be able to store whatever information has been entered so that it doesn't disappear after page refresh. I am trying to use localstorage but so far I cannot get it to print the information after page load.

I really have tried many options already and this is what I am working with now.

Please note, the code has been minimalised to make it easier to deal with.

I appreciate the help.

EDIT:If I try console.log or alert I get a null message.

let retrieveBookShelf = localStorage.getItem("storedbookShelf");

let bookShelf = JSON.parse(retrieveBookShelf);


const
  shelf = document.getElementById('shelf')
, addBookBtn = document.getElementById('add-book')
, myForm = document.getElementById('form')
, formDiv = document.getElementById('formcontainer')
, submitFormBtn = document.getElementById('submitform')
, booksElms = [];


class BookDetails {
    constructor(title){
        this.title = title
    }
}

addBookBtn.addEventListener('click', () => 
  {
 
  let book = document.createElement('div');
  book.classList.add('book');
  shelf.appendChild(book);
  booksElms.push(book);
  });


myForm.addEventListener('submit', e =>
  {
  e.preventDefault();
  booksElms.forEach( book =>
    {
    if ( book.textContent == '' )  // set value if empty
      book.textContent = myForm.booktitle.value; 
    });

    var title = document.getElementById("booktitle").value;

newBookAdd = new BookDetails(title);
bookShelf.push(newBookAdd);
var storeBooks = JSON.stringify(bookShelf);
  
localStorage.setItem("storedbookShelf", (storeBooks));
  
  });



  console.log(bookShelf);
#shelf {
    height: 150px;
    border-bottom: 5px solid #000;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(25px,40px));
    align-items: end;
  margin-bottom: 15px;
}

.book {
    border: 1px solid #000;
    height: 100px;
    width:25px;
    display: inline-block;
  padding-top: 5px;
    writing-mode: vertical-rl;
    font-family: 'Roboto', sans-serif;
}

#add-book {
  margin-bottom: 15px;
}
<div id="bookshelf">

                    <div id="shelf"></div>
                    
                </div>

<button id="add-book">+</button>

<form id="form" >

                        <label for="booktitle">Book Title</label><br>
                        <input type="text" id="booktitle" name="booktitle"><br>

                        <input type="submit" id="submitform" value="Submit">
                        

                    </form>


Solution

  • Here is an example of how to save and print your bookcase.

    Live example here (wihout limit on local storage usage): https://jsfiddle.net/wpexpert/wftjvc3p/

    const
        localStorageKey = 'storedbookShelf',
      shelf = document.getElementById('shelf'),
      addBookBtn = document.getElementById('add-book'),
      clearBooksBtn = document.getElementById('clear-books'),
      myForm = document.getElementById('form'),
      formDiv = document.getElementById('formcontainer'),
      submitFormBtn = document.getElementById('submitform'),
      booksElms = [];
    
    const retrieveBookShelf = localStorage.getItem(localStorageKey);
    let bookShelf = retrieveBookShelf ? JSON.parse(retrieveBookShelf) : [];
    
    class BookDetails {
      constructor(title) {
        this.title = title
      }
    }
    
    function addBookFnc(title) {
      let book = document.createElement('div');
      book.classList.add('book');
      if (title) {
        book.textContent = title;
      }
      shelf.appendChild(book);
      booksElms.push(book);
    }
    
    addBookBtn.addEventListener('click', () => {
      addBookFnc();
    });
    
    if (bookShelf) {
      bookShelf.forEach(book => {
        addBookFnc(book?.title);
      });
    }
    
    clearBooksBtn.addEventListener('click', () => {
        localStorage.removeItem(localStorageKey);
    });
    
    myForm.addEventListener('submit', e => {
      e.preventDefault();
    
      let hasEmptyBook = false;
    
      booksElms.forEach(book => {
       // set value if empty
        if (book.textContent == ''){
          book.textContent = myForm.booktitle.value;
            hasEmptyBook = true;
        }
      });
    
      if (hasEmptyBook === false) return '';
    
      let title = document.getElementById("booktitle").value;
    
      newBookAdd = new BookDetails(title);
      bookShelf.push(newBookAdd);
      const storeBooks = JSON.stringify(bookShelf);
    
      localStorage.setItem(localStorageKey, (storeBooks));
    
    });
    
    console.log(bookShelf);
    #shelf {
      height: 150px;
      border-bottom: 5px solid #000;
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(25px, 40px));
      align-items: end;
      margin-bottom: 15px;
    }
    
    .book {
      border: 1px solid #000;
      height: 100px;
      width: 25px;
      display: inline-block;
      padding-top: 5px;
      writing-mode: vertical-rl;
      font-family: 'Roboto', sans-serif;
    }
    
    #add-book {
      margin-bottom: 15px;
    }
    <div id="bookshelf">
      <div id="shelf"></div>
    </div>
    <button id="add-book">+</button>
    <form id="form">
      <label for="booktitle">Book Title</label><br>
      <input type="text" id="booktitle" name="booktitle"><br>
      <input type="submit" id="submitform" value="Submit">
    </form>
    
    <button id="clear-books">Clear-books</button>