Unable to retrieve the contents of a previous shopping cart

I need to update my shopping cart. I am trying to retrieve the information from my old cart, but for some reason, it's not working properly and I keep getting a quantity of 1.

Below is the code for the app.post request:

app.post("/add-to-cart/:id", async (req, res) => {
  try {
    // fetch your data
    const id = req.params.id,
      { data } = await axios.get("http://localhost:4200/products"),
      singleProduct = await data.find((product) => product._id === id);

    // create/get a cart
    let cart;
    if (!req.session.cart) {
      req.session.cart = cart = new Cart({});
    } else {
      // req.session does not save the Cart object, but saves it as JSON objects
      cart = new Cart(req.session.cart ? req.session.cart : {});
    }
    console.log("This is variable cart: ",cart)
    cart.addProduct(singleProduct);
    res.redirect("/");
    console.log(req.session)
  } catch (error) {
    console.log(error);
  }
});

There seems to be an issue here:

let cart = new Cart(req.body.cart ? req.body.cart : {});

Here is the output of console.log:

https://i.sstatic.net/cfj12.png

This is the code for the Cart :

module.exports = function Cart(oldCart) {
    this.productItems = oldCart.productItems || {};
    this.totalQty = oldCart.totalQty || 0.00;
    this.totalPrice = oldCart.totalPrice || 0.00;
    
    this.addProduct = function(item) {
        
        let storedItem = this.productItems;
              
        if (!storedItem){
            storedItem = this.productItems = {item: item, qty: 0, price: 0};
        }
        else{
            storedItem.qty++;
            this.totalQty ++;
           storedItem = {item: item, qty: storedItem.qty, price: storedItem.price}
            
            storedItem.price = storedItem.item.price * storedItem.qty;
            
            console.log("item from database",storedItem)
            
            this.totalPrice += storedItem.item.price;
        }
    }

    };

Answer №1

If you want to store session data on the server-side per session/user, consider using the express-session package.

const session = require("express-session");

app.use(session({
  secret: "some secret"
}));

app.post("/add-to-cart/:id", async (req, res) => {
  try {
    // fetch your data
    const id = req.params.id,
      { data } = await axios.get("http://localhost:4200/products"),
      singleProduct = await data.find((product) => product._id === id);

    // create/get a cart
    let cart;
    if (!req.session.cart) {
      cart = new Cart({});
    } else {
      cart = new Cart(req.session.cart);
    }
    req.session.cart = cart;
    cart.addProduct(singleProduct);
    res.redirect("/");
  } catch (error) {
    console.log(error);
  }
});

To retrieve the cart data when needed, you can create a path for that:

app.get("/get-cart", (req, res) => {
  const cartData = req.session.cart || {};
  res.send(JSON.stringify(cartData));
});

In the provided code, there are some issues with the Cart class.

For setting default values of totalQty and totalPrice, avoid using

oldCart.totalQty || oldCart.totalQty==0.00
. Instead, consider:

Rework the addProduct function to properly handle the stored item.

module.exports = function Cart(oldCart) {
  this.productItems = oldCart.productItems || {};
  this.totalQty = oldCart.totalQty || 0;
  this.totalPrice = oldCart.totalPrice || 0.00;

  this.addProduct = function(item) {
    let storedItem = this.productItems[item];
    if (!storedItem) {
      storedItem = this.productItems[item] = { item: item, qty: 1, price: item.price };
      this.totalQty++;
      this.totalPrice += item.price;
    } else {
      storedItem.qty++;
      storedItem.price += item.price;
      this.totalQty++;
      this.totalPrice += item.price;
    }
  };
};

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

having trouble accessing my Node.js API after deploying my project on the Heroku server

I recently completed a project where I am managing data in my AWS dynamoDB. At first, everything was running smoothly as I fetched all the data through the database and listed the items. However, things took a turn when I deployed the project on Heroku. Up ...

Need assistance with jQuery AJAX?

Hey there, I'm a new member and I've gone through the different Ajax Help topics but still can't figure out why my code isn't working. Here's what I have: $(document).ready(function(){ $.ajax({ type: "GET", ur ...

Error: The object being referenced (scope.awesomeThings) is undefined and unable to be evaluated

Each time I run the grunt test command, I encounter this error. I set up a project using yo angular and attempted to execute the example code provided in Yeoman's scaffold. Something seems to have gone awry here - below is the code snippet that I trie ...

Ionic 5 page div within ion-contents element is experiencing scrolling issues on iPhone devices

My application features a div element containing an ion-slides component. The ion-slides component houses several ion-slide elements that slide horizontally. Here is the relevant code snippet: <ion-content [scrollEvents]="true"> <div ...

Effortlessly showcase JSON data in an HTML owl carousel

Is there a way to display JSON data in HTML format? I have a JSON file containing reviews from Facebook, and I would like to showcase them on my website. Each review should be placed in its own div element. The JSON data below is extracted from the Faceboo ...

There seems to be an issue with FastAPI not sending back cookies to the React

Why isn't FastAPI sending the cookie to my React frontend app? Take a look at my code snippet: @router.post("/login") def user_login(response: Response, username :str = Form(), password :str = Form(), db: Session = Depends(get_db)): use ...

Analyzing data visualization within CSS styling

I have the desire to create something similar to this, but I am unsure of where to start. Although I have a concept in mind, I am struggling to make it functional and visually appealing. <div id="data"> <div id="men" class="shape"></di ...

Excessive geolocation position responses in Angular 5

I am trying to implement an Angular 5 component that will continuously fetch my current location every 3 seconds if it has changed. Here is a snippet of my code: export class WorkComponent implements OnInit { constructor(private userService: UserService ...

Is there a way to mount or unmount a React component by pressing a single key?

I am currently developing an application that showcases 3D objects upon pressing certain keys on the keyboard. My goal is to have these objects disappear after 2-3 seconds or once the animation completes. Below is the component responsible for managing th ...

Configuring CSP in NUXT

Encountering CSP blocking with my local js files. Below is my nuxt.config.js: unsafeInlineCompatibility: true, policies: { 'default-src': ["'self'", 'delivly.com', 'localhost', '*.gstatic.co ...

Create various designs for a section of a webpage

My goal is to create a coding playground using flex-box to position different panels. Here is an example in JSBin, with the following html code: <div class="flex-box"> <div class="col" id="html-panel"> <p>html</p> </div& ...

difficulty associated with using a package I uploaded to npm

I am encountering issues with importing a package that I have published on npm. after executing npm install binaryconversor I have experimented with various ways of incorporating it. let conversor = require('binaryconversor'); let conversor = ...

Issue with async waterfall not triggering the next callback function when combined with a promise

async.waterfall(eventIDs.map(function (eventId) { console.log(eventId); return function (lastItemResult, nextCallback) { if (!nextCallback) { nextCallback = lastItemResult; las ...

Extract JSON data from a third-party website using JavaScript

I'm facing a challenge parsing JSON from an external website using JavaScript or jQuery for a Chrome extension. Specifically, I need to extract the number from an external URL with the JSON {"_visitor_alertsUnread":"0"} and assign that number to a var ...

What is the method for acquiring a dynamic segment in the router of a Next.js 13 application?

Currently in my project, I am using the new App Router in Next.js 13 and MongoDB as the DBMS to fetch data via API. When trying to retrieve all data from a collection, it is successful. However, fetching only one data results in failure. The error message ...

Having trouble with submitting an Ajax form to a MySQL database

My expertise lies in PHP and HTML, but I'm currently learning JavaScript. I'm facing a challenge with creating a form that can submit data to be inserted into MySQL without reloading the page (using AJAX). Here is the form I have: <form id=" ...

Integrating Next.js with a authentication provider and a Redux provider

During the development of my Next js project, I incorporated Next auth using import {Provider} from 'next-auth/client' to wrap the <Component /> in _app.js. However, I also want to integrate Redux into the project. This involves importing ...

Implementing Kendo UI dataSource to interact with a PHP function

Greetings Everyone, I have a category.php file within my code that handles CRUD functions. However, I am unsure how to call these functions in the Kendo UI dataSource/transport. Previously, I had separated the PHP files, but now I want to consolidate them ...

Exploring ways to modify the default Keep Alive behavior in Express JS

While stress testing a nodejs express server, I discovered that it automatically includes a "Connection: Keep-Alive" header. However, my application only needs to expose a web api to the client and does not require the connection to remain open after recei ...

The Fetch API's Post functionality is currently experiencing issues

fetch('http://localhost:9000/api/app/contact', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: this.state.email, contactNumber: ...