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

Alert when counter reaches 0 fails

I try to add a feature to my simple Counter (React) App which alerts when counter reaches 0 onClick increase or decrease button. But alert always late for 1 click. How can I fix it?
Here is my code:

function App() {
  const [counter, setCounter] = useState(0);

  function handleIncrement() {
    setCounter((oldState) => oldState + 1);
    if (counter === 0) alert('it is 0');
  }

  function handleDecrement() {
    setCounter((oldState) => oldState - 1);
    if (counter === 0) alert('it is 0');
  }

  return (
    <div>
      <button onClick={handleIncrement}>increment</button>
      <div>{counter}</div>
      <button onClick={handleDecrement}>decrement</button>
    </div>
  );
}

I want to see alert exactly when I see 0 on the screen. But the code above shown alert only after the counter passed zero.

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 :

This is happening bcoz setCounter is async operation.
We can fix this using this two ways

  1. wrap alert function inside the setCounter’s callback.

    function handleIncrement() {

    setCounter((oldState) => {

    if (oldState + 1 === 0) {
    
      alert('it is');
    
    }
    
    return oldState + 1;
    

    });

    }

    function handleDecrement() {

    setCounter((oldState) => {

    if (oldState - 1 === 0) {
    
      alert('it is');
    
    }
    
    return oldState - 1;
    

    });

    }

  2. you can also use useEffect to achieve this

    useEffect(() => {

    if (counter === 0) {
    
      alert('it is');
    
    }
    

    }, [counter]);

    function handleIncrement() {

    setCounter(counter + 1);
    

    }

    function handleDecrement() {

    setCounter(counter - 1);
    

    }

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