最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to make setState in React synchronous Process - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 5

I 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
        })
   );
}
发布评论

评论列表(0)

  1. 暂无评论