React.js, wait for setState to finish before triggering a function? React.js, wait for setState to finish before triggering a function? reactjs reactjs

React.js, wait for setState to finish before triggering a function?


setState() has an optional callback parameter that you can use for this. You only need to change your code slightly, to this:

// Form Inputthis.setState(  {    originId: input.originId,    destinationId: input.destinationId,    radius: input.radius,    search: input.search  },  this.findRoutes         // here is where you put the callback);

Notice the call to findRoutes is now inside the setState() call,as the second parameter.
Without () because you are passing the function.


       this.setState(        {            originId: input.originId,            destinationId: input.destinationId,            radius: input.radius,            search: input.search        },        function() { console.log("setState completed", this.state) }       )

this might be helpful


According to the docs of setState() the new state might not get reflected in the callback function findRoutes(). Here is the extract from React docs:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

So here is what I propose you should do. You should pass the new states input in the callback function findRoutes().

handleFormSubmit: function(input){    // Form Input    this.setState({        originId: input.originId,        destinationId: input.destinationId,        radius: input.radius,        search: input.search    });    this.findRoutes(input);    // Pass the input here}

The findRoutes() function should be defined like this:

findRoutes: function(me = this.state) {    // This will accept the input if passed otherwise use this.state    if (!me.originId || !me.destinationId) {        alert("findRoutes!");        return;    }    var p1 = new Promise(function(resolve, reject) {        directionsService.route({            origin: {'placeId': me.originId},            destination: {'placeId': me.destinationId},            travelMode: me.travelMode        }, function(response, status){            if (status === google.maps.DirectionsStatus.OK) {                // me.response = response;                directionsDisplay.setDirections(response);                resolve(response);            } else {                window.alert('Directions config failed due to ' + status);            }        });    });    return p1}