Home > Software engineering >  counter function give me minus value
counter function give me minus value

Time:12-26

I have a counter function, the counter will run when user hold the button. The problem here is when user hold the button decrement, the counter will keep going even when the value hit 0, and it give me the minus value, which is I don't want that.

I have give the condition for that case, but I think there's something wrong with my approach.

here's the Codesandbox

Was wondering if there's something I missed..

CodePudding user response:

if (value > 0) {
     setValue((prev) => prev - incrementBidValue);
  } else if (value === 0) {
  setValue(0);
}

Try replacing your code with below one,

setValue((prev) => (prev - incrementBidValue) <= 0 ? 0 : (prev - incrementBidValue);

CodePudding user response:

I did just edit your decrement() function in which you decrement the value state. I added a ternary operation which checks if the prevValue - 0.1 is going to be greater or equal than 0, if so it will run the decrement function, otherwise it will return 0 and not go into any negative value. Here is the full code from your App.js:

import React from 'react';

export default function App() {
  const [value, setValue] = React.useState(0);
  const timer = React.useRef(null);

  const increment = () => {
    timer.current = setInterval(() => setValue((prev) => prev   0.01), 10);
  };

  const decrement = () => {
    timer.current = setInterval(
      // Here we check to see if the minus operation results in a negative value or not
      // if it is going to bigger or equal to 0 we will do the decrements
      // else we will return 0
      () => setValue((prev) => (prev - 0.01 >= 0 ? prev - 0.01 : 0)),
      10
    );
  };

  function timeoutClear() {
    clearInterval(timer.current);
  }

  return (
    <div className="App">
      <button
        onm ouseLeave={timeoutClear}
        onm ouseUp={timeoutClear}
        onm ouseDown={decrement}
      >
        Decrement
      </button>
      <span style={{ fontSize: 24, fontWeight: 600, margin: '0px 10px' }}>
        {value.toFixed(2)}
      </span>
      <button
        onm ouseLeave={timeoutClear}
        onm ouseUp={timeoutClear}
        onm ouseDown={increment}
      >
        Increment
      </button>
    </div>
  );
}

  • Related