I'm currently building a CRUD app so users can keep track of books they have read or haven't read. Im currently trying to implement an update/edit feature so the user can update the book info if he/she wishes. The issue I'm having is, whenever I try to save the book info after changing the input values, the last book in 'myLibrary' array would get the info instead of the current book I'm trying to update. The only time the current book gets the user input is when it's the only book in the array :(
I tried using the array splice() method to replace the current book with a new book that has the new info/values but I'm still having the same problem.
// book class: represents a book
class Book {
constructor(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}
}
// array to store books.. default books using the Book Constructor
let myLibrary = [{
title: 'Dark Matter',
author: 'Blake Crouch',
read: 'read',
pages: 342,
},
{
title: '1984',
author: 'Geroge Orwell',
read: 'not read',
pages: 328
},
];
/* saves the updated user input on click and closes modal
removes the book from the library array and adds the updated book to the library array and saves it to local storage again with updated info from user input in the form fields in the modal window and closes the modal window after submission of the form fields */
saveBtn.addEventListener('click', (index) => {
myLibrary.splice(myLibrary.indexOf(index), 1);
addBookToLibrary();
setData();
render();
document.querySelector('.modal').classList.add('modal--hidden');
hideBackgroundFade();
clearForm();
});
Difficult to say w/o more code, esp. the HTML structure or a framework you might use. So assuming the following HTML structure:
<div class='books'>
<div book-id="123">
<h1>Title 1</h1>
<p>200 pages</p>
</div>
<div book-id="456">
<h1>Title 2</h1>
<p>100 pages</p>
</div>
</div>
To be most generic, i.e. any click would link your UI to the data source, your script might could look sg like:
const books = document.querySelector('.books');
books.addEventListener("click", evt => {
const book = evt.target.closest("[book-id]");
if (book) {
const bookId = book.getAttribute("book-id");
const bookInLib = myLibrary.find( elem => elem.id == bookId )
// here you update your book and trigger rendering
}
})