Showing a notification on the screen upon redirection to the index page

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.

Answer №1

If you're trying to pass a data object using the res.redirect method to your views, it won't work that way. You'll need to approach this problem in a linear manner. When defining your router.post("/book/:title"...) function, simply include a query parameter like the book title:

if (existingBook) {
  return res.redirect(`/?duplicate=${existingBook.title}`);
}

Next, update your router.get("/")... to always check for a query parameter called duplicate:

app.get('/', async (req, res, next) => {
   const duplicate = req.query.duplicate ?? false; // Using the Nullish coalescing operator (??)
   
   if(duplicate !== false){ // Check if duplicate has a value
    res.render("index", { duplicate });
   } else{
      // Proceed with your normal code execution
      //...
   }
}); 

In your index page, utilize ejs to verify the presence of the duplicate object and show a message accordingly:

<% if (duplicate) { %>
   <div id="message">The Book <%= duplicate %> was already added to your library</div>
<% } %>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Open the CSV document

Why am I receiving an error stating ./vacancy-data.csv cannot be found when attempting to pass the csv file into the csvtojson npm package? The csv file is located in the same directory as the code below: var express = require('express'), route ...

"Error: Command 'npm' is not recognized as a valid internal or external command" encountered while using create-react-app

Why won't npm work for me? I've been trying to dive into the world of React and kickstart my learning journey. With Node installed, along with the create-react-app package, I thought I was all set. When I run commands like npm -v or create-reac ...

Is the key to achieving optimal client interactions within a client layout, while still maintaining its role as a server component, truly possible?

My current challenge involves managing modals opening and closing with server components instead of client components. In the past, I used to lift the state up to my Layout for client components: export default function Layout({ children }) { const [showP ...

callback triggering state change

This particular member function is responsible for populating a folder_structure object with fabricated data asynchronously: fake(folders_: number, progress_callback_: (progress_: number) => void = (progress_: number) => null): Promise<boolean ...

Employing an object from a distinct module

After creating a function to parse objects and provide getters, I encountered an issue. I need to access this object from a different module without re-parsing it each time. Is there a way to achieve this without using a global variable? var ymlParser = r ...

Would you prefer to generate fresh HTML using JavaScript or dynamically load an existing HTML layout using AJAX?

I have a project where I need to generate a large amount of HTML that isn't currently on the page. Up until now, I've been using jQuery to construct the page piece by piece with JavaScript, adding divs and adjusting layouts as needed. Lately, I ...

searching for a document in mongodb that matches a particular id and username

{ "data": [ { "_id": 555, "username": "jackson", "status": "i am coding", "comments": [ { "user": "bob", "comment": "bob me " }, { ...

Struggling with displaying values from an array using getJSON

I've encountered an issue with displaying the results of a $.getJSON call. The code I have retrieves JSON data from a specific page. var loadItems = function() { if (hasNextPage === false) { return false } pageNum = pageNum + 1; var url = baseUr ...

When a change is made in the parent component, the local state of the child component in ReactJS is automatically updated

I'm currently facing a challenge while implementing a custom dropdown filter for a table in react. Each column has a set of dropdown values with an Apply button. To handle this, I've created a child component that takes the dropdown values and s ...

A comprehensive guide on creating a package that combines an href link with an <li> element

I am currently using the <li> tag to display href links. The issue I am facing is that when I click on the 'box,' it does not directly link to another page. Instead, I have to click on the href link for it to redirect to another page. Is th ...

Tracking the progress bar as files are being uploaded via AJAX using HTML5

Currently, I have a progress bar that increments based on the number of files and their sizes. I am looking to implement an overall progress bar to display while uploading files to the server using AJAX and HTML5. Each file is uploaded individually to th ...

The Quivering Quandaries of Implementing Jquery Accordions

For a demonstration of the issue, please visit http://jsbin.com/omuqo. Upon opening a panel by clicking on the handle, there is a slight jitter in the panels below during the animation. In the provided demo, all panels should remain completely still as t ...

Virtual machines have encountered issues when attempting to utilize setTimeout within the browser with vm.runInNewContext

When running a JS script using the vm module in a browser, the following details are included: vm.runInNewContext(codeToEval, sandboxObject); Although interval methods like setTimeout and setInterval do not work, even when exposed in the sandboxObject cr ...

Why is my filtering and sorting function failing to function properly?

I have a collection of events represented by an array of objects, where each event contains a start date and an end date. My goal is to filter out any events that have already passed based on the current time (now), and then sort the remaining events in d ...

Disable the toggling of the dropdown functionality in the bootstrap function

Recently, I made some modifications to a bootstrap navbar by transforming it into a toolbar and adjusting a dropup dropdown to include two datepicker elements. An issue arose when the dropdown would collapse upon selecting a date. To address this problem, ...

ESLint's no-unused-vars rule is triggered when Typescript object destructuring is employed

I'm encountering an issue with my Typescript code where I am destructuring an object to extract a partial object, but it's failing the linter check. Here is the problematic code snippet: async someFunction(username: string): Promise<UserDTO> ...

Tips on sorting an array within a map function

During the iteration process, I am facing a challenge where I need to modify certain values based on specific conditions. Here is the current loop setup: response.result.forEach(item => { this.tableModel.push( new F ...

Transferring a JavaScript variable to PHP using Ajax within the same webpage

Check out my HTML and JavaScript code: <form id="form" action="javascript:void(0)"> <input type="submit" id="submit-reg" value="Register" class="submit button" onclick="showtemplate('anniversary')" style='font-family: georgia;font- ...

What is the process for generating SDF-Icons (Mapbox's specialized icons) from PNG files?

I am currently working on changing the icon color of an icon image in Mapbox. According to Mapbox documentation, the only way to do this is by using sdf-icons (https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#paint-symbol-icon-color). After hours o ...

Toggle between different socket.io servers for seamless connectivity

I'm looking for help with a situation where I need a socket.io client to connect to server A, disconnect, and then connect to server B. Any ideas on how I can achieve this? Thanks in advance! UPDATE: Attached below is the code snippet that's gi ...