I am trying to run the code above but the state get updated only for idx. From what i understand the second function's setState will not get the updated state and thats why this happens. Is there a way to make it work properly (expect than merge the 2 functions in one)
doIt(idx,array) {
this.doFirst(array);
this.doSecond(idx);
}
doFirst(array){
//bla bla bla code
this.setState(test: {...this.state.test, array});
}
doSecond(idx) {
// bla bla bla code
this.setState(test: {...this.state.test, idx});
}
setState() is 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.
it takes an optional callback function that will be executed once setState is completed and the component is re-rendered. you can use that callback.
If the next state depends on the previous state, it is recommended to use the updater function form setState(updater[, callback])
doIt(idx,array) {
this.doFirst(array, () => this.doSecond(idx));
}
doFirst(array, callback){
//bla bla bla code
this.setState(firstUpdaterFunction, callback);
}
doSecond(idx) {
// bla bla bla code
this.setState(2ndUpdaterFunction);
}
References: