Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to update state and take a decision on updated state in react native

I am using the Picker component in my app. And there is list view on the screen. Based on the selected value of the Picker, list view gets updated. Here is the code

<Picker style={{ flex: 0.3, marginTop: -10 }}
  selectedValue={this.state.helpModel.needyType}
  onValueChange={(itemValue, itemIndex) => {
    this.setState((prevState) => {
      return { helpModel: { needyType: itemValue, helpStatus: prevState.helpModel.helpStatus } }
    });
    this.getNeedies(this.state.helpModel);
  }}>
  {this.state.helpCategory.map((data, index) => {
    return (
      <Picker.Item key={data.id} label={data.title} value={data.value} />
    );
  })}
</Picker>

I have used state variable (this.state.helpModel.needyType) to bind the selectedValue of the picker and on the onValueChange I am updating the state variable. Then a method is called based on the this.state.helpModel that will get the list data and update the list view. But helpModel is not getting the update immediately so it retains the previous values for a time but in that time getNeedies method is called and based on the previous value data is requested.

May be this is because setState is of async behaviour. I have solved this using to call getNeedies method after some 2-3 seconds using setTimeout. But is there any better or elegant way to do the same? May be .then like in promises?

I have just started with React Native, so please ignore if this is too basic to ask.

like image 474
Sunil Garg Avatar asked Nov 03 '25 16:11

Sunil Garg


2 Answers

Since setState works in an asynchronous way. That means after calling setState the this.state is not immediately changed. So if you want to perform an action immediately after setting state, use 2nd argument as callback on setState. Consider this example:

this.setState({
    data: newData
}, () => {
  //TODO: Do something with this.state here
});
like image 132
Pir Shukarullah Shah Avatar answered Nov 05 '25 07:11

Pir Shukarullah Shah


Changing the state through setState method does not immediately update the state of the app. A callback function is to be used.

this.setState({value: event.target.value}, function () {
    console.log(this.state.value);
});

Here is Link in detail if you want to follow.

like image 24
Sagaryal Avatar answered Nov 05 '25 07:11

Sagaryal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!