2

I have issue with SegmentedControl component in React Native.

<SegmentedControlIOS style={styles.SegmentedControlIOS}
    values={['All', 'Recent']}
    selectedIndex={this.state.selectedIndex}
    onChange={this._handleChangeSegment.bind(this)}
/>

_handleChangeSegment(event) {
    console.log(event.nativeEvent.selectedSegmentIndex, "nativeEvent");
    this.setState({
        isLoading: true,
        selectedIndex: event.nativeEvent.selectedSegmentIndex
    });
    console.log(this.state.selectedIndex, "state");
    this.fetchData();
}

The problem here is the value of nativeEvent.selectedSegmentIndex and my selectedIndex state, in the console I have :

By default selectedIndex state is set to 1 (Recent) in the constructor.
When I click 'All' the console.log return

0, 'nativeEvent'
1, 'state'

So the nativeEvent is correct but it seems not to be updated in my state and I don't know why.
Could you please help me with that ?

In the fetchData method I check if the selectedIndex state is 1 or 0 to call an ajax request but it doesn't load the good request because the state value is not the nativeEvent.selectedSegmentedIndex.

Regards.

Rtransat
  • 43
  • 6

1 Answers1

0

From https://facebook.github.io/react/docs/component-api.html

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

Therefore, console.log(this.state.selectedIndex, "state") is not necessarily going to return the mutated state.

If you need access to the mutated state, you can pass a callback function as a second argument to setState - this callback function will be executed after the state has been mutated.

Chi
  • 22,624
  • 6
  • 36
  • 37