On my main index page, there are 18 divs representing different books. When a user clicks on a div, they can see details about the book such as title, author, and summary. There's also an option to add the book to a Collections array by clicking the "Add to Library" button. The user profile page displays the Collections array sorted by most recent additions, allowing users to view which books have been added to their library.
GET request for book page.
router.get("/book/:title", async function (req, res, next) {
const bookId = parseInt(req.params.title);
const book = data.PopularBooks.find((book) => book.id === bookId);
res.render("book", { book });
});
POST request for book page.
router.post("/book/:title", async (req, res, next) => {
try {
const user = await User.findById(req.user.id);
if (!user) {
return res.status(404).send("User not found");
}
const existingBook = user.book.find(
(book) => book.title === req.body.title
);
if (existingBook) {
return res.redirect("/");
}
const newBook = {
title: req.body.title,
image: req.body.image,
};
user.book.push(newBook);
await user.save();
res.redirect("/");
} catch (error) {
res.status(500).send("Error adding book");
}
});
There is also a hidden message div in the index page that displays a message.
<div id="message">Book already added to library</div>
If a user tries to add a book to the Collections array that is already added, they are redirected to the index page. I am exploring ways to change the display of the message from hide to block after two unsuccessful attempts at adding the same book to the array. This will help clarify to the user that the book is already in their library rather than assuming an error occurred.