Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
Change a single product quantity using state (react)

So ,I wanted to change this one product object in the UI with a button click, and reduce the quantity of the product. But the quantity amount did not change .What is the best move in situations like that.

let product={ a:1,b:2,c:3}; 

Lets say changing the value.

b:5; 
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

please check this sample code

import React, { useState, useEffect } from 'react';

export default function App() {
  const [products, setProducts] = useState([
    { name: 'Product 1', qty: 1, price: 10 },
    { name: 'Product 2', qty: 1, price: 20 },
  ]);

  const [totalAmt, setTotalAmt] = useState(0);

  useEffect(() => {
    const total = products.reduce((s, i) => s += i.price * i.qty, 0);
    setTotalAmt(total);
  }, [products]);

  const incrQty = (index) => {
    setProducts((v) => {
    const a = JSON.parse(JSON.stringify(v)); // FOR AVOIDING MUTATING DATA, BECAUSE IN STRICT MODE THIS SETSTATE CALLBACK WILL TRIGGER TWICE
      a[index].qty += 1;      
      return [...a];
    });
  };

  const decrQty = (index) => {
    setProducts((v) => {
    const a = JSON.parse(JSON.stringify(v));
      a[index].qty -= 1;      
      return [...a];
    });
  };

  return (
    <div>
      Total Amount: Rs.{totalAmt}
      <ul>
        {products.map((e, k) => (
          <li key={k}>
            {e.name}, qty={e.qty}, subtotal {e.qty * e.price},
            <button onClick={e => incrQty(k)}>Incr Qty</button>
            {
              (e.qty > 1)?<button onClick={e => decrQty(k)}>Decr Qty</button>:null
            }
          </li>
        ))}
      </ul>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda