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;

>Solution :

 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
    }

Leave a Reply