ujuy
ujuy

Reputation: 65

counter function give me minus value

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..

Upvotes: 0

Views: 86

Answers (3)

DSDmark
DSDmark

Reputation: 1261

Hi @ujuy,

Did you trying to implement a counter, that increments or decrements by a fixed amount when the user holds down a button? To prevent the counter from going below zero. You could add the condition when you set the value in setValue like this.

const decrement = () => {
 timer.current = setInterval(() => {
  if (value > 0) {
   setValue((prev) => {
    let preValue = prev - 0.01
    if (preValue < 0) {
     return 0
    }
    return preValue
   })
  }
  if (0 >= value) {
   setValue(0)
  }
 }, 10)
}

Upvotes: 0

score30
score30

Reputation: 304

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
        onMouseLeave={timeoutClear}
        onMouseUp={timeoutClear}
        onMouseDown={decrement}
      >
        Decrement
      </button>
      <span style={{ fontSize: 24, fontWeight: 600, margin: '0px 10px' }}>
        {value.toFixed(2)}
      </span>
      <button
        onMouseLeave={timeoutClear}
        onMouseUp={timeoutClear}
        onMouseDown={increment}
      >
        Increment
      </button>
    </div>
  );
}

Upvotes: 0

Vinal Lathiya
Vinal Lathiya

Reputation: 46

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);

Upvotes: 1

Related Questions