admin管理员组文章数量:1415064
In my application, I need to convert async to sync (i.e) once setState set the value then I need to fetch the data from api in post call
logChange(val) {
this.setState({
fetchIntentReport: {
startDate: this.state.fetchIntentReport.startDate,
endDate: this.state.fetchIntentReport.endDate,
intents: val.split(','),
},
});
this.props.fetchIntentReports({
startDate: this.state.fetchIntentReport.startDate,
endDate: this.state.fetchIntentReport.endDate,
intents: this.state.fetchIntentReport.intents,
});
}
Once value has set to intents then i need to call fetchIntentReports api call via redux.
In my application, I need to convert async to sync (i.e) once setState set the value then I need to fetch the data from api in post call
logChange(val) {
this.setState({
fetchIntentReport: {
startDate: this.state.fetchIntentReport.startDate,
endDate: this.state.fetchIntentReport.endDate,
intents: val.split(','),
},
});
this.props.fetchIntentReports({
startDate: this.state.fetchIntentReport.startDate,
endDate: this.state.fetchIntentReport.endDate,
intents: this.state.fetchIntentReport.intents,
});
}
Once value has set to intents then i need to call fetchIntentReports api call via redux.
Share Improve this question asked Jul 11, 2017 at 17:42 KARTHI SRVKARTHI SRV 4994 silver badges20 bronze badges 2- 1 The setState method accepts a callback as a second parameter. There is no way to make it really synchronous, as explained in the docs it is more of a request. – Leandro Commented Jul 11, 2017 at 17:49
- Once an API is asynchronous, that's it. That's the way the library works and you pretty much have to adapt to it. – ggorlen Commented Aug 22, 2021 at 22:56
1 Answer
Reset to default 5I highly remend against forcing a synchronous call. Fortunately, setState
allows callback functions so you can do the following:
logChange(val) {
var startDate = this.state.fetchIntentReport.startDate;
var endDate = this.state.fetchIntentReport.endDate;
var intents = val.split(',');
this.setState({
fetchIntentReport: {
startDate,
endDate,
intents
}
}, () => {
// if you need the updated state value, use this.state in this callback
// note: make sure you use arrow function to maintain "this" context
this.props.fetchIntentReports({
startDate,
endDate,
intents
})
);
}
本文标签: javascriptHow to make setState in React synchronous ProcessStack Overflow
版权声明:本文标题:javascript - How to make setState in React synchronous Process - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744676186a2619123.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论