Reputation: 257
I have a checkbox that calling two functions on on press event , in the first function I am changing the state of the component , on the second function I am calling that state to see if it has been changed by the first function, by displaying the state of that component by console.log I see that changes are displayed only after second click on the checkbox , so first click empty data displayed , seconde click data and changes are displayed on the console , would you please help me understand why there is that time lag ?
this is my code :
<CheckBox onPress={() => {this.treggerCheckBoxcallback(item); this.editeTask()}} />
//function 1
treggerCheckBoxcallback = tsk => {
let currentTasks = tsk;
this.setState({ currentTask : currentTasks});
};
// function 2
editeTask = () => {
console.log(this.state.currentTask);
}
Upvotes: 1
Views: 1373
Reputation: 3009
the function setState
is asynchronous, so your console log shows the state right before the setState is really called. To avoid such behavior you can use setState like this:
this.setState({ data: yourData }, () => {
console.log(this.state.data)
// code called after the setState is finished. (callback)
})
Upvotes: 3