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
})
);
}