Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
How to make data of a cart to increase dynamically?

I'm trying to make cart items to stack dynamically every time on function call: addProduct(). The data which I want to work with was captured successfully but the problem is that on each function call the quantity always remains 1.

This is the logic which I implemented:

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 = {item: item, qty: 0, price: 0}; 
        /*Using this storedItem qty: 0, price: 0 for testing*/
   
        if (!storedItem){
            storedItem = this.productItems = {item: item, qty: 0, price: 0};
        }
        storedItem = {item: item, qty: storedItem.qty, price: storedItem.price}

        storedItem.qty++;
        storedItem.price = storedItem.item.price * storedItem.qty;
        this.totalQty ++;
        this.totalPrice += storedItem.price;
        
        //this.productItems += storedItem;
        console.log("Product items: ",this.productItems)
        
    }

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

When I remove line: let storedItem = this.productItems = {item: item, qty: 0, price: 0}; the result remains NaN. So how to solve this problem? Because the items are still at the quantity of 1 no matter how many API calls do I make.

Here is my app.post call:

app.post('/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("console log cart",cart);
    console.log(req.body);
  } 
  
  catch (error){
    console.log(error)
  }
  
});

Here is my console.log result (every time the same):

enter image description here

How to solve this issue?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your implementation of the Cart function seems to be fine. I'm wondering however if you're sending the correct data to your back end at each code. You could try to console log req.body.cart and check that it contains the previous content of the cart.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda