By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Javascript – How to perform calculations with useState variables that handle increment and decrement
JavaScript

Javascript – How to perform calculations with useState variables that handle increment and decrement

Admin
Last updated: 2024/01/12 at 2:34 PM
Admin
Share
3 Min Read
How to perform calculations with useState variables that handle increment and decrement

Problem:

What my code wants to achieve is — when I click the increment button, the increment value quantityCount is used to multiply the object sellingPrice. But what I get is — the initial value of the quantityCount multiplies the sellingPrice, but when I increase the count quantityCount it doesn’t dynamically multiply the sellingPrice object as shown in the console.

Contents
Problem:Solution:

Would appreciate your help on this, thanks.

  const [productName, setProductName] = useState("");
  const [sellingPrice, setSellingPrice] = useState(0);
  const [quantityCount, setQuantityCount] = useState(0); //useState Variable handling my Increment and Decrement
  const [newItems, setNewItems] = useState([])

  const enterProductName = (e) =>{
      setProductName(e.target.value);
  }
  const enterSellingPrice = (e) =>{
      let sellingPricePerEach = e.target.value
      setSellingPrice(sellingPricePerEach * quantityCount);

      console.log(sellingPricePerEach * quantityCount);
  }
  let handleSaveItem = () => {
      const newItemData = {productName, sellingPrice,quantityCount};
      setNewItems([...newItems, newItemData]);
      console.log(newItemData);
  }
  let incrementQuantity = () =>{
      setQuantityCount(quantityCount+ 1);
      //console.log(quantityCount+ 1);
  }
  let decrementQuantity = () =>{
      setQuantityCount(quantityCount- 1);
     // console.log(quantityCount- 1);

  }

//JSX
<div>Items</div>
{newItems.map((items)=>{
    const {productName,sellingPrice, quantityCount} = items;
    return(
        <>
        <div>
        <div><div>{productName}</div>
            <div>{sellingPrice}</div>
        </div>
        <div><FontAwesomeIcon icon={faTrashCan} /></div>
        
    </div>
    
    </>
    );
})}

//JSX
<div>Quantity</div>
<div>
  <FontAwesomeIcon icon={faPlus} onClick={incrementQuantity}/>
    {quantityCount}
  <FontAwesomeIcon icon={faMinus} onClick={decrementQuantity}/>
</div>

Solution:

Jacob already answered the question, but here is the answer to extend his comment — use useEffect

The reason it doesn’t work from your original logic is the state stays the same (in this case, quantityCount) until the next render. That is why when you clicked “Increment”, the quantityCount being used is still the old one rather than the updated one you’ve been expecting.

In this case, we need a way to “watch” the quantityCount, so when we can update the sellingPrice as quantityCount changes.

This can be achieved by adding the following lines in your component —

useEffect(()=>{
  if (quantityCount === 0) return // safeguard invalid value
  setSellingPrice(quantityCount * sellingPrice)
}, [quantityCount])

(Unrelated — useReducer is another technique for increment and decrement a state, but it a bit overkill for the simple state management in this component)

Example code https://codesandbox.io/s/wild-butterfly-9vmp2x?file=/src/App.tsx

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article Easier way to enable styling based on component attributes being present or not Javascript – Easier way to enable styling based on component attributes being present or not
Next Article I tried to have 2 buttons, one changing the bgcolor of body to white, the other to black (i want a light mode and dark mdeo for my website) Javascript – I tried to have 2 buttons, one changing the bgcolor of body to white, the other to black (i want a light mode and dark mdeo for my website)
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?