I am trying to save input values submitted through form into local storage in the form of the array, but once the form is submitted again, the saved value in local storage gets changed with the new submitted value as the
function bookDetails(bookName,bookAuthor,bookType) {
this.name = bookName;
this.author = bookAuthor;
this.type = bookType;
}
let libraryForm = document.getElementById("bookForm");
libraryForm.addEventListener("submit", libraryBooksDetails);
function libraryBooksDetails(e,index) {
e.preventDefault();
console.log("The book details have been submitted");
let bookName = document.getElementById("bookName").value;
let bookAuthor = document.getElementById("author").value;
let bookType;
let fiction = document.getElementById("Fiction");
let programming = document.getElementById("ComputerProgramming");
let personal = document.getElementById("PersonalDevelopement");
if(fiction.checked){
bookType = fiction.value;
}
else if(programming.checked){
bookType = programming.value;
}
else if(personal.checked){
bookType = personal.value;
}
// BookDetails Object
let book = new bookDetails(bookName,bookAuthor,bookType);
let bookData = ""
bookData = bookData || [];
let nameOfBooks = bookData.concat(bookName)
// let nameOfBooks = bookData
// nameOfBooks.push(book.bookName);
localStore.setItem("books",JSON.stringify(nameOfBooks))
console.log(book);
let display = new Display()
display.add(book);
display.clear();
}
Thanks
I'm not sure I understand the question completely because you are setting the value let book = new bookDetails but that is not what you are storing in local storage.
// First time bookData value is set, this is always an empty string
let bookData = "";
// Since empty string is a falsey value, bookData value is re-set to an empty array
bookData = bookData || [];
// nameOfBooks is initialised as an array with one value of bookName
let nameOfBooks = bookData.concat(bookName);
// books key in local storage is a stringified array with one item
localStore.setItem("books", JSON.stringify(nameOfBooks));
localStorage.setItem(key, value) will always replace the existing value at that key. If you want to append to the stored value, first get the value and parse it before appending the new value.
const oldValue = localStorage.getItem('books');
const parsed = JSON.parse(oldValue);
const newValue = parsed.concat(nameOfBooks);
localStorage.setItem('books', JSON.stringify(newValue));