skip to Main Content

I have an issue with Switch component from react native, the issue is user able to multiple click on switch component before API completed. So, how to prevent user to multiple click on switch component?

I’m using class component btw.

              <Switch
                trackColor={{ false: MONOCHROME_5, true: POLYCHROME_1 }}
                ios_backgroundColor={MONOCHROME_5}
                onValueChange={() => {
                  //do something
                }}
                onChange={(e) => console.log(e)}
                value={this.state.enabled}
              />

Already try to use state to disable the component with onTouchStart props, but it was still able to multiple click

2

Answers


  1. Chosen as BEST ANSWER

    I got the answer from my partner

    here is the way

                  <Switch
                    disabled={this.state.isDisableToggle}
                    onResponderStart={() => {
                      if (Platform.OS === 'ios') { // handle prevent click toggle for ios activated
                        this.setState({ isDisableToggle: true })
                      }
                    }}
                    onChange={() => {
                      if (Platform.OS === 'android') { // handle prevent click toggle android activated
                        this.setState({ isDisableToggle: true })
                      }
                    }}
                    onValueChange={() => {
                      setTimeout(() => { // handle prevent click toggle disabled
                        this.setState({ isDisableToggle: false });
                      }, 2000);
                      // do something
                    }}
                    value={this.state.isEnabledSwitch}
                  />
    

    it was almost same with concept from @Stitt, but we found out how to prevent double click from iOS and android device


  2. Use a useState hook to hold the state of a boolean value which will set the switch’s disabled prop. You can then toggle this boolean in your onChange or onValueChange function to disable the switch, and then re-enable once the API call has completed.

    const [switchDisabled, setSwitchDisabled] = useState(false)
    
    <Switch
        trackColor={{ false: MONOCHROME_5, true: POLYCHROME_1 }}
        ios_backgroundColor={MONOCHROME_5}
        onValueChange={() => {
            setSwitchDisabled(true)
            //await API Call
            setSwitchDisabled(false)
        }}
        onChange={(e) => console.log(e)}
        value={this.state.enabled}
        disabled={switchDisabled}
    />
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search