Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
React setState doesnt update data immediately

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!