0

im new to React JS and i found a problem while updating my object using setState

const [quantity, setQuantity] = useState(0);
    const [product, setProduct] = useState<Product>(products[0]);    
    const [transactionDetail, setTransactionDetail] = useState<TransactionDetails>({
        product,
        id: 0,
        price: 0,
        quantity: 0,
    })
    
    const addProduct = () => {        
        let price = (product.price * quantity);        
        setTransactionDetail({...transactionDetail,quantity: quantity, product:product, price: price });
        console.log(transactionDetail);        
    };

i must call addProduct function twice to update the object, I've read some answers, but I still don't understand how to use useEffect and callbacks, can anybody help me?

Sheva Athalla
  • 47
  • 1
  • 7

1 Answers1

0

//use a useEffect hooks to automatically watchout for change and set it back to the new updated state

const [quantity, setQuantity] = useState(0);
    const [product, setProduct] = useState<Product>(products[0]);    
    const [transactionDetail, setTransactionDetail] = useState<TransactionDetails>({
        product,
        id: 0,
        price: 0,
        quantity: 0,
    })
    const addProduct = () => {        
        let price = (product.price * quantity);        
        setTransactionDetail({...transactionDetail,quantity: quantity, product:product, price: price });
        console.log(transactionDetail);        
    };
useEffect(() => {setTransactionDetail(transactionDetail)}, [transactionDetail])

Rashdev
  • 1
  • 1
  • i'm sorry sir, but how do i use the function? – Sheva Athalla Dec 01 '21 at 13:28
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 01 '21 at 15:49