Skip to content Skip to sidebar Skip to footer

React Native Put A "cooldown" On A Button

my question is if it is possible to put a cooldown on a button that the user presses, or to only register like 1 press in 2 seconds. I am using React Native (Expo) connected with a

Solution 1:

Make the button disabled as soon as it's pressed.

constMyComponent = ({makePutCall}) => {
   const [disabled,setDisabled] = useState(false);

   const doPut = async () => {
       setDisabled(true);
       awaitmakePutCall();
       setDisabled(false);
   }

   return<Buttondisabled={disabled}onPress={doPut}/>
 
}

or use a ref to prevent pushing more than once:

constMyComponent = ({makePutCall}) => {
   const disabled = useRef(false);

   const doPut = async () => {
       if(disabled.current) return;
       disabled.current = true;
       awaitmakePutCall();
       disabled.current = false;
   }

   return<ButtononPress={doPut}/>
 
}

My person favourite is a spinner, like you said:

constMyComponent = ({makePutCall}) => {
   const [showSpinner,setShowSpinner] = useState(false);

   const handlePress = async () => {
      setShowSpinner(true);
      awaitmakePutCall();
      setShowSpinner(false);
   }

   return showSpinner ? <Spinner/> : <ButtononPress={handlePress}/>
}

or do it another way - DON'T USE A TIMER.

Solution 2:

There are 2 solutions I can think of as of now, there might be many other solution as well.

Solution 1: Have some variable which can keep a value if database call has already been done, once you get response from database you can reset that variable and user can press that button again.

Something like

onPress = {this.state.isPressed ? null : <this.writeTodatabase>}

and

writeTodatabase = () => {
    this.setState({ isPressed:true })
    // code to write to database// once you have response from database you can set isPressed to false.
}

You can also disable button if that variable is true.

Solution 2: You can use throttle from lodash library.

Reference Document

Solution 3:

try using debounce/throttle. here is a basic example of debounce.

Import * as _ from lodash;
...
...

      
onPressDebounced = _.debounce(this.onPressed(),500);

render() { 
  return ( 
    <TouchableHighlight 
      { ...this.props } 
      onPress = { this.onPressDebounced}> 
      {this.props.children} 
    </TouchableHighlight>
  )
}

Post a Comment for "React Native Put A "cooldown" On A Button"