Reputation: 49
I am having trouble with being able to set the state of a variable inside a function after that function is called and has a value passed to it.
I'm not sure what I'm doing wrong here, I've tried a lot of different things and looked at lots of different examples but can't seem to get it to work.
Heres the function I'm calling:
_onSectionListPress = function(id) {
const tempID = id;
this.setState({ jobId: tempID });
alert(this.state.jobId);
};
And here is where I'm calling the function from and passing a value into it:
<FlatList
style={styles.jobs}
data={this.state.data}
renderItem={({ item }) => (
<TouchableOpacity
onPress={this._onSectionListPress.bind(this, item.id)}
>
<ListItem
title={`${item.text}`}
/>
</TouchableOpacity>
)}
keyExtractor={extractKey}
/>
I have also tried not using
onPress={ this._onSectionListPress(item.id) }
Any help is greatly appreciated
Upvotes: 0
Views: 692
Reputation: 3048
I think what you may be running into is that setState
is actually asynchronous.
Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
setState
can have a second parameter which is a callback after the change has been applied. Try using the code below and see if you have more luck:
_onSectionListPress = function(id) {
this.setState({ jobId: id}, () => alert(this.state.jobId));
};
Upvotes: 2