如何在更改值之前使Switch组件异步等待成功响应?

时间:2019-04-21 12:57:39

标签: javascript react-native

默认的开关流将在按下该值后立即对其进行切换。

我要执行以下逻辑

  1. 按下开关
  2. 不要更改值
  3. 打开警报框
  4. 如果可以,请发送发布请求以切换数据库值
  5. 成功响应后,允许更改开关值

我可以获得成功的响应并更新开关,但是一旦按下开关,该值就会切换两次,并且我想暂停此行为,直到获得成功的响应。尝试异步等待,尝试将开关包装在可触摸的状态,没有反馈...现在需要帮助

<Switch 
   value={this._getSwitchValue(id)} 
   onValueChange={() => this._toggleSwitch(id)}
/>

  /**
   * Toggle the Switch - Send post request to database
   */
  _toggleSwitch (id) {
    Alert.alert('Notice!', 'Do you really want to change this setting?',
    [
      { text: "OK", onPress: () => this.props.toggleSettingsSwitch(id, this.props.token) },
      { text: "Cancel", onPress: () => console.log("cancel pressed")}
    ],
    { cancelable: true }
  )}

1 个答案:

答案 0 :(得分:0)

更改发出请求的函数中的Switch值。

toggleSettingsSwitch = async (value) => {

  const response = await this.changeSettingsRequest(); // making a call

  // here add a check, if request was successful change switch value
  // if (response.ok) {
  // this.setState({ switchValue: value });
  //}

};

_toggleSwitch = (value) => {
  Alert.alert(
    'Notice!',
    'Do you really want to change this setting?',
    [
      {
        text: 'OK',
        onPress: () => {
          this.toggleSettingsSwitch(value);
        },
      },
      { text: 'Cancel', onPress: () => console.log('cancel pressed') },
    ],
    { cancelable: true }
  );
};

<Switch
  onValueChange={this._toggleSwitch}
  value={this.state.switchValue}/>

snack example