Shopping cart has encountered an issue with storing the data correctly

  • While I've managed to successfully integrate another service, the challenge now lies in implementing the logic for correctly generating cart items. My goal is to increment the quantity of items in the cart by one with each function call, but it seems that approach isn't working as expected.
  • When using Postman, I consistently receive the ID of the selected data, which is precisely what I need.
  • How can I create a totalQty variable that increases by 1 every time the function is invoked?

I'm currently retrieving information from another service and attempting to integrate it into an existing function called AddProduct().

app.get('/add-to-cart/:id', async (req, res) => {
  try {
    let id = req.params.id;
    let cart = new Cart(req.body.cart ? req.body.cart : {});

    const { data } = await axios.get('http://localhost:4200/products');
    const singleProduct = await data.find((product) => product._id === id)
    
    cart.addProduct(singleProduct, singleProduct._id);
    
    req.body.cart = cart;

    res.redirect('/');
    console.log(req.body.cart);
  } 
  
  catch (error){
    console.log(error)
  }
  
});

Here's the logic behind adding items to the cart:

module.exports = function Cart(oldCart) {
    this.productItems = oldCart.productItems || {};
    this.totalQty = oldCart.totalQty || oldCart.totalQty==0.00;
    this.totalPrice = oldCart.totalPrice || oldCart.totalPrice==0.00;
   
    this.addProduct = function(item, id) {
        let storedItem = this.productItems;
        storedItem = this.productItems = {item: item, qty: 0, price: 0};
        
        if (!storedItem){
            storedItem = this.productItems = {item: item, qty: 0, price: 0};
            console.log("stored is empty")
        }
        else{
        
        console.log("Stored item full!")
        storedItem = this.productItems = {item: item, qty: storedItem.qty, price: storedItem.price}

        storedItem.qty++;
        storedItem.price = storedItem.item.price * storedItem.qty;
        
        this.totalQty ++;
        this.totalPrice += storedItem.price;
        
    }
    }

    this.generateArray = function () {
        let arr = [];
        for (let id in this.productItems) {
            arr.push(this.productItems);
        }
        return arr;
    }};

These are the results displayed with console.log

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

Answer №1

It seems like the reason behind consistently getting a total quantity of 2 every time you test is due to calling addProduct once and then again on the next line with cart.addProduct in the console log. To prevent double adding, it's recommended to store the results first and then console log.

cart.addProduct(singleProduct, singleProduct._id);
console.log(cart.addProduct(singleProduct, singleProduct._id)); // Remove this line

Update your code as follows:

const response =  cart.addProduct(singleProduct, singleProduct._id);
console.log('Cart response: ', response);

Update 2 I have identified the issue; the persistent totalQty of 1 is because a new cart is created on each API call.

Update 3 Updated your addProduct code: Upon reviewing the code, I found some errors e.g.

storedItem = this.productItems = {item: item, qty: 0, price: 0}; 

module.exports = function Cart(oldCart) {
    this.productItems = oldCart.productItems || {};
    this.totalQty = oldCart.totalQty || oldCart.totalQty==0.00;
    this.totalPrice = oldCart.totalPrice || oldCart.totalPrice==0.00;
   
    this.addProduct = function(item, id) {
        let storedItem =  {item: item, qty: 0, price: 0};
        // Update here        
        if (this.productItems){
 
          console.log("Stored item full!")
          storedItem = {item: item, qty: storedItem.qty, price: storedItem.price}
        }
        console.log("totalQty: ",this.totalQty);

        console.log("Quantity 1: ",storedItem.qty);
        storedItem.qty++;
        console.log("Quantity 2: ",storedItem.qty);
        storedItem.price = storedItem.item.price * storedItem.qty;
        
        this.totalQty ++;
        this.totalPrice += storedItem.price;
        
    }

    this.generateArray = function () {
        let arr = [];
        for (let id in this.productItems) {
            arr.push(this.productItems);
        }
        return arr;
    }};
    

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

Attempting to show different fields depending on the chosen option

Having an issue with the signup process for my team and competition setup. I want to implement a feature where, if the user selects 'Competition', the promo code field will be displayed. However, this field should only appear when 'Competiti ...

Exploring the world of JSON and JavaScript data structures

Can someone provide some clarification please? var a = '{"item":"earth", "color":"blue", "weight":920}'; Is the data type of a a string or an array ? var b = JSON.parse(a); What is the data type of b - an object or an array ? ...

Obtain the content of a dynamic text input field from a nested directive

I recently developed a custom directive using AngularJS that contains a child directive. The child directive's main task is to create various dynamic input elements like textboxes, radio buttons, and checkboxes, each with default values sourced from a ...

How can the .pre() middleware function in Mongoose be utilized?

I'm curious about the use cases for mongoose .pre('validate') and .pre('save'). I understand their functionality, but I'm struggling to think of specific scenarios where I would need to utilize them. Can't all necessary a ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

Issue with ChartJs version 2.8.0: The custom tooltip remains visible even when clicking outside the chart canvas or moving the mouse pointer

I am utilizing ChartJs to display a line chart with a custom tooltip that appears upon the click event of the data points. The challenge I am facing is that the custom tooltip remains visible even when the mouse pointer is outside the chart canvas area. ...

Retrieving all options from a dropdown list in HTML using ASP.net C#

I am currently working with a select list that looks like this: <select name="Section" id="Section" size="5"> <option>Section1</option> <option>Section2</option> <option>Section3</option> <option>Section4< ...

modifying input field with radio button selection in Jquery

Is there a way to set the input field to have a default value and then change it, or disable it with a different value? $("#tax").value(19).prop("disabled",false); $("#tax").value(0).prop("disabled",true); <script src="https://ajax.googleapis.com/aj ...

Learn the steps to import and utilize individual BootStrap 5 JavaScript Plugins

I am currently diving into the world of Bootstrap (v5.1.0) and gulp, but I'm a bit confused about how to import specific Bootstrap JavaScript plugins. I attempted to bring in only the modal plugin from Bootstrap, but encountered either a syntax error ...

What's the Deal with Blank Square Brackets in JavaScript?

While browsing through , I stumbled upon this code snippet: useEffect(() => { const interval = setInterval(() => { console.log('This will run every second!'); }, 1000); return () => clearInterval(interval); }, []); I am intri ...

In Angular 2+, what is the comparable counterpart to Vue's Vuex?

I have experience with Vue's Vuex, but I am currently working on an Angular application. I would like to implement a similar principle where all components are managed from one central location (like a store in Vue). Is there an alternative to Vuex in ...

Mastering SVG Path Coordinates using Pure JavaScript

Is it possible to target and manipulate just one of the coordinate numbers within an SVG path's 'd' attribute using JavaScript? For example, how can I access the number 0 in "L25 0" to increment it for animating the path? function NavHalf ...

How about this: "Effortlessly upload files by simply dragging and dropping them from your computer to

Currently, I am facing a challenge in uploading a picture from my PC to a website that utilizes a drag and drop interface. Despite using Javascript to open the required link, set properties, and click on the upload field, a file manager window appears wh ...

Comparing jQuery AJAX with UpdatePanel

Our team is facing the challenge of dealing with a page containing an overwhelming amount of jQuery code (specifically around 2000 lines) that has become difficult to maintain. We are considering shifting some of this functionality to the server side for ...

What could be causing my Ionic button to not initialize in the expected state while using ngIf with a boolean property connected to an Ionic checkbox?

I'm currently in the process of setting up a list of ingredients with checkboxes and conditional buttons, but I'm facing some challenges with the default state. Ideally, I only want the button to be visible when the checkbox is unchecked so that ...

Extracting web search result URLs using Puppeteer

I'm currently facing an issue with the code I've written for web scraping Google. Despite passing in a specific request, it is not returning the list of links as expected. I am unsure about what might be causing this problem. Could someone kindly ...

Error: Laravel Pusher Authorization Failed

My events are not working properly on my laravel 7.x setup with pusher and laravel-echo. I have double-checked everything and even set the broadcast driver to pusher in the .env file, but still getting a 401 error. If anyone has any insights or solutions, ...

Switching colors after uncovering text using JavaScript

I'm striving to achieve specific results with my code, but I'm having trouble pinpointing what exactly I'm doing wrong. Any guidance on how to correct my approach would be greatly appreciated. Currently, I've created rows that can be c ...

jQuery performs perfectly in Chrome but encounters issues in IE9/IE8 and other older versions of Internet

I've implemented this lengthy jQuery script to enable dynamic dropdown loading and updating when selections are changed. However, I'm facing issues in Internet Explorer where the script loads the dropdowns initially but doesn't trigger oncha ...

What is the correct way to test setInterval() statements within Angular?

Here is a simple code snippet I am working on: public async authenticate(username: string, password: string) { const authenticationResponse = await this.dataProvider.authenticate(username, password); if (authenticationResponse.result.code == 0) { ...