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

how to validate after checkboxed clicked?

I broke my Code down to make it look simple


  const [factor, setfactor] = useState(1);
  const [nullify, setNullify] = useState(1);

  const Price = 10;
  const Bonus = 15;
  const finalPrice = (Price * factor - Bonus) * nullify;
// start         5 = (10 * 2 -15)* 1
// after Click  -5 = (10 * 1 -15)* 1
//what i want    0 = (10 * 1 -15)* 0

   const handleFactor = () => {
    setfactor(1)
    validate()
  };

  const validate = () => {
    if (finalPrice <= 0) {
      setNullify(0);
    }
  };

  useEffect(() => {
    handleFactor();
  }, [factor]);
  //HTML Stuff
  return (
    <>
      <input type="checkbox" onClick={handleFactor} />
      <input type="checkbox" onClick="activate bonus" />


      {finalPrice}
    </>
  );

I want, if the bonus make it below 0 the final price should not be a minus number , instead it should becomes a zero itself – but it doesn’t work.

I know, that the final price will be 5 when the validation do it’s thing. But how do I get the newPrice?

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 :

State updates are asynchronous, so you can get the updated state on the next render. When you do this

const handleFactor = () => {
  setfactor(1)
  validate()
};

the state haven’t updated yet, and validate would use the previous (valid) values. You’ll need to move validate to the next render for this to work.

However, you don’t need another state to ensure that finalPrice is above 0. Use Math.max(price * factor – bonus, 0)to get the max between the final price and0` (or any other minimum number):

const { useState, Fragment } = React;

const Demo = ({ price, bonus }) => {
  const [factor, setfactor] = useState(2);

  const finalPrice = Math.max(price * factor - bonus, 0);

  const handleFactor = () => {
    setfactor(1)
  };

  return (
    <Fragment>
      <input type="checkbox" onClick={handleFactor} />
      {finalPrice}
    </Fragment>
  );
};

ReactDOM
  .createRoot(root)
  .render(<Demo price={10} bonus={15} />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

<div id="root"></div>
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