SegmentedControlIOS forceUpdate

198 Views Asked by At

I react-native's SegmentedControlIOS component for choosing between three values which works fine so far. However, when my application is loading data I want to ensure that the user can not change the value associated with that control as this would cause concurrency issues and interrupts the update.

Thus I decided that the method for handling the control's value change only calls the callback supplied via a property if the loading process is currently not active. Otherwise, I call this.forceUpdate() in order to rerender the host component which includes setting the selectedIndex property of the segmented control. However, when this.forceUpdate is invoked the selected index does not change. Therefore, I decided to print the value selectedIndexis set to which always displays the initial (wished) index.

Below you can see the code of my rendering method for displaying the segmented control:

render: function()
{
    ...
    var indexBluetoothAutostart = 0;
    switch (this.props.data.BluetoothAutostartState)
    {
        case BluetoothAutostartState.OFF:
            indexBluetoothAutostart = 1;
            break;
        case BluetoothAutostartState.ON:
            indexBluetoothAutostart = 2;
            break;
        case BluetoothAutostartState.AUTO:
            indexBluetoothAutostart = 0;
            break;
    }
    console.log("index: " + indexBluetoothAutostart);
    ...
    return (
        ...
        <SegmentedControlIOS selectedIndex={indexBluetoothAutostart}
            momentary={false}
            onValueChange={(newValue) => this.changeBluetoothAutostartState(newValue)}
            values={[Localization.HomeFragment.BluetoothAutostartState.btnAuto, Localization.HomeFragment.BluetoothAutostartState.btnOff, Localization.HomeFragment.BluetoothAutostartState.btnOn]}/>
    );
}

Finally, the following snippet shows the onValueChange handler:

changeBluetoothAutostartState: function(newValue)
{
    if (newValue === Localization.HomeFragment.BluetoothAutostartState.btnAuto)
    {
        if (this.props.bluetoothConnectionBusy === true)
        {
            Toast.display(Localization.BluetoothOperationInProgress.msgWaitForUploadToFinishToast);
            this.forceUpdate();
        }
        else
        {
            this.props.onBluetoothAutostartStateChange(BluetoothAutostartState.AUTO);
        }
    }
    // process the other two options
    ...
}

I appreciate any help. Thanks in advance.

1

There are 1 best solutions below

0
On BEST ANSWER

I simply added a timestamp variable initialized with 'Date.now()' to the class' state and instead of invoking 'this.forceUpdate' I updated the state's timestamp:

this.setState({ timestamp: Date.now() });