0

I have a simple state where each property of the object should have a min-max value of 0 - 100. Aka volume between 0-100, etc. Right now if I decrease the volume, it goes negative. Where could I set a minimum value for this?

  const [controls, setControls] = useState({
    volume: 0,
    bass: 0,
    mid: 0,
    treble: 0,
  });

  const volumeDecrease = () => {
    setControls({
      volume: controls.volume - 1,
    });
  };
Király Roland
  • 141
  • 2
  • 9
  • 3
    Simple: Don't allow the `setControls` call to happen if `controls.volume` is 0. See also [this.state inside setState ReactJS](https://stackoverflow.com/questions/51817798/this-state-inside-setstate-reactjs) and [react docs -- state updates may be asynchronous](https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous) – ggorlen Jun 06 '21 at 21:34

1 Answers1

1

You could wrap a conditional around the set state function.

  const [controls, setControls] = useState({
    volume: 0,
    bass: 0,
    mid: 0,
    treble: 0,
  });

  const volumeDecrease = () => {
    if(volume > 0 && volume < 100){
        setControls({
          volume: controls.volume - 1,
        });
    }

  };
Colin McGovern
  • 105
  • 1
  • 6