Search code examples
react-nativepickersetstate

React-native: Picker onValueChange setState lagging, do I need a setTimeout?


In my React-native project I have a picker that, behind the scenes, chooses an array to use in a function.

 <Picker
      style={styles.onePicker} itemStyle={styles.onePickerItem}
      selectedValue={this.state.food}
      onValueChange={(itemValue) => { this.setState({food: itemValue}); this.cuisine();}}
    >
      <Picker.Item label="Italian" value="Italian" />
      <Picker.Item label="Chinese" value="Chinese" />
      <Picker.Item label="Cajun" value="Cajun" />
      <Picker.Item label="KFC" value="KFC" />
    </Picker>

It all works, but the setState does not get assigned before the function is run. In use, the array used is one picker section/action behind what's shown.

Is it normal to need a setTimeout, or whatever is used in react, for Pickers?

I also tried passing the itemValue in the cuisine function this.cuisine(itemValue);

which calls:

cuisine = (data) => { the function stuff }

but in the console or in an alert to show the data passed I only get

 [object Object]

and not the actual value.

I'm a bit green in the use of ES6 and React.


Solution

  • Use this it is working perfectly for me

     <View>
            <Picker        
              selectedValue={this.state.food}
              onValueChange={(itemValue) => {  this.cuisine(itemValue);}}>
              <Picker.Item label="Italian" value="Italian" />
              <Picker.Item label="Chinese" value="Chinese" />
              <Picker.Item label="Cajun" value="Cajun" />
              <Picker.Item label="KFC" value="KFC" />
      </Picker>
    
          <Text>{this.state.food}</Text>
    
      </View>
    

    and now in the cuisine function

    cuisine = (itemValue: any) => { 
       this.setState({food: itemValue});   
       console.log(this.state.food);
    }