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

200
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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