Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useState for both increasing and decreasing number?

just a stupid question from me, how do guys use the useState hook and prevent it from decreasing under negative number, For example, I got the block codes like this:

const [amount, setAmount] = useState(1);
    const handleSetAmount = () => {
            if (amount > 0) {
                return setAmount(amount + 1)
            } else {
                return 0;
            }
    }

   return (
      <AmountContainer>
         <Remove onClick={() => setAmount(amount -1)}/>
         <Amount>{amount}</Amount>
         <Add onClick={handleSetAmount}/>
      </AmountContainer>
      <Button>ADD TO CART</Button>
)

I want the state to stand still 0 if users press on the Remove button (preventing it from showing negative number), press on Add button It will increase 1, but when I wrote like that It didn’t work. So anyone here know how to do it please help me, thanks! :3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here’s a sample of the thing which you want to achieve:

import { useState } from "react";


export default function App() {
  const [state, setState] = useState(1);
  const decrease = () => {
    if (state == 0) return;
    setState(state - 1);
  };
  const increase = () => {
    setState(state + 1);
  };
  return (
    <>
      <button onClick={increase}>+</button>
      <button onClick={decrease}>-</button>
      {state}
    </>
  );
}

Edit nice-sutherland-mgms7

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading