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

201
Vistas
React state not updating correctly. Increase and decrease function does not work on first click, but works after subsequent clicks

React state not updating correctly. Increase and decrease function does not work on first click, but works after subsequent clicks. Subtotal value is always wrong. if quantity is 10 subtotal should be 105. But subtotal shows as 94.50

import React from "react";
import { Card, Button, CardDeck } from 'react-bootstrap';
import { useState } from "react";

import image from "../images/image.PNG";
import "./productcard.css";

function ProductCard() {
    const price = Number(10.50);
    const [quantity, setQuantity] = useState(0);
    const [subtotal, setSubtotal] = useState(0);
    function calculatesubtotal() {
        const sub = quantity * price;
        setSubtotal(sub);
    }
    function increase() {
        setQuantity(quantity+ 1 );     
        calculatesubtotal();   
    }
    function decrease(e) {
        setQuantity(quantity- 1);
        calculatesubtotal();
        e.stopPropagation();
    }

    return (
        <Card className="card" onClick={increase}>
  <Card.Img className="image" variant="top" src={image} />
  <Card.Body className="body">
    <Card.Title className="title">White Bread 700g</Card.Title>
  </Card.Body>
  <label className="quantity-label">QTY</label>
  <div className="quantity-area">
  <Button className="increase-button" variant="primary" onClick={increase}>+</Button>
  <input className="quantity" type="number" value={quantity}/>
  <Button className="decrease-button" variant="primary" onClick={decrease}>-</Button>
  </div>
  <label className="price-label" >Price</label>
  <input className="price" type="number" value={price} />  
  <label className="subtotal-label" >Subtotal</label>
  <input className="subtotal" type="number" value={subtotal}/>
    
    
</Card>
    );
}

export default ProductCard;
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

 function increase() {
        setQuantity(quantity+ 1 );     
        calculatesubtotal();   
    }

Because here when you update the quantity, the quantity read inside the calculatesubtotal still refers to the old value. You can pass the new value to calculatesubtotal and use that inside.

function increase() {
        let newQt = quantity+ 1 ;
        setQuantity(newQt);     
        calculatesubtotal(newQt); // Modify calculatesubtotal accordingly
    }
about 4 years ago · Juan Pablo Isaza Denunciar

0

When you have a value that depends directly from another state value, it's a good practice to do not duplicate it at state, but just perform the calculation every time the state value changes:

    const price = Number(10.50);
    const [quantity, setQuantity] = useState(0);

    function increase() {
        setQuantity(quantity+ 1 );     
    }
    function decrease(e) {
        setQuantity(quantity- 1);
        e.stopPropagation();
    }

    const subtotal = useMemo(() => quantity * price,[quantity])

Way less code and a declarative approach.

about 4 years ago · Juan Pablo Isaza Denunciar

0

USe useEffect hook instead of calculatesubtotal function as bellow

import React,{useEffect} from "react";

...

uesEffect(()=>{
setSubtotal(quantity * price);
},[quantity]]
import React,{useEffect} from "react";
import { Card, Button, CardDeck } from 'react-bootstrap';
import { useState } from "react";

import image from "../images/image.PNG";
import "./productcard.css";

function ProductCard() {
    const price = Number(10.50);
    const [quantity, setQuantity] = useState(0);
    const [subtotal, setSubtotal] = useState(0);

    uesEffect(()=>{
        setSubtotal(quantity * price);
    },[quantity]]

    function increase() {
        setQuantity(quantity+ 1 );     
    }
    function decrease(e) {
        setQuantity(quantity- 1);
        e.stopPropagation();
    }

    return (
        <Card className="card" onClick={increase}>
  <Card.Img className="image" variant="top" src={image} />
  <Card.Body className="body">
    <Card.Title className="title">White Bread 700g</Card.Title>
  </Card.Body>
  <label className="quantity-label">QTY</label>
  <div className="quantity-area">
  <Button className="increase-button" variant="primary" onClick={increase}>+</Button>
  <input className="quantity" type="number" value={quantity}/>
  <Button className="decrease-button" variant="primary" onClick={decrease}>-</Button>
  </div>
  <label className="price-label" >Price</label>
  <input className="price" type="number" value={price} />  
  <label className="subtotal-label" >Subtotal</label>
  <input className="subtotal" type="number" value={subtotal}/>
    
    
</Card>
    );
}

export default ProductCard;

explaination

whenever there is a change in quantity this useEffect will get called and update the subtotal base on latest quantity

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