2

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.

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. 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. Commented Aug 22, 2021 at 22:56

1 Answer 1

5

I highly recommend 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
        })
   );
}
Sign up to request clarification or add additional context in comments.

1 Comment

@KARTHISRV awesome! Let me know if you need anything else!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.