KARTHI SRV
KARTHI SRV

Reputation: 499

How to make setState in React synchronous Process

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.

Upvotes: 2

Views: 7437

Answers (1)

Dom
Dom

Reputation: 40459

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

Upvotes: 5

Related Questions