score:300
setState()
has an optional callback parameter that you can use for this. You only need to change your code slightly, to this:
// Form Input
this.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.
score:1
Why not one more answer? setState()
and the setState()
-triggered render()
have both completed executing when you call componentDidMount()
(the first time render()
is executed) and/or componentDidUpdate()
(any time after render()
is executed). (Links are to ReactJS.org docs.)
Example with componentDidUpdate()
Caller, set reference and set state...
<Cmp ref={(inst) => {this.parent=inst}}>;
this.parent.setState({'data':'hello!'});
Render parent...
componentDidMount() { // componentDidMount() gets called after first state set
console.log(this.state.data); // output: "hello!"
}
componentDidUpdate() { // componentDidUpdate() gets called after all other states set
console.log(this.state.data); // output: "hello!"
}
Example with componentDidMount()
Caller, set reference and set state...
<Cmp ref={(inst) => {this.parent=inst}}>
this.parent.setState({'data':'hello!'});
Render parent...
render() { // render() gets called anytime setState() is called
return (
<ChildComponent
state={this.state}
/>
);
}
After parent rerenders child, see state in componentDidUpdate()
.
componentDidMount() { // componentDidMount() gets called anytime setState()/render() finish
console.log(this.props.state.data); // output: "hello!"
}
score:10
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
}
score:11
setState
takes new state and optional callback function which is called after the state has been updated.
this.setState(
{newState: 'whatever'},
() => {/*do something after the state has been updated*/}
)
score:18
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
score:22
If someone here landed and having the same situation using hooks, the same behavior can be achived via the below process
const [data, setData] = useState(false);
useEffect(() => {
doSomething(); // This is be executed when the state changes
}, [data]);
setdata(true);
Here useEffect
will run after any change in data, and we can execute any dependent task.
Source: stackoverflow.com
Related Query
- React Hooks - useReducer: Wait for reducer to finish before triggering a function
- React.js, wait for setState to finish before triggering a function?
- How to wait for getDownloadURL to finish in my mapping function before updating my object array in react state?
- Wait for function to setState before triggering next function
- JS unit testing using enzyme: how to wait for setState within component's method to finish before proceeding with test case
- How to wait for React useEffect hook finish before moving to next screen
- Wait for multiple async calls to finish before React render
- React wait for async function to finish in order to setup DOM references
- React wait for useEffect to finish before return
- Using promises in React to wait for functions to finish within JavaScript map function
- React Redux with Redux Observable wait for authentication action to finish before continuing
- Proper way to wait for a function to finish or data to load before rendering in React?
- React TS: wait for props before calling function with props as arguments
- How to make Jest wait for all asynchronous code to finish execution before expecting an assertion
- ReactJs: How to wait for componentDidMount() to finish before rendering?
- Wait for CSS to load before JS in React [FOUC]
- How to wait for .map() to finish executing before continuing on to next lines of code
- Wait for API call data before render react hooks
- React - wait for promise before render
- React Hooks: how to wait for the data to be fetched before rendering
- Wait for a React Component to finish updating
- Wait for external script to load before the React component
- React waiting for map function before deciding render to prevent div flash
- Wait for API data before render react hooks
- React with conditional promises chain and wait for them all before send dispatch
- React - Async api call, Promise.all wait for calls to finish
- Wait until `this.state` has been set for time period before running function
- Wait for a Javascript function to finish executing and fetch the response from it
- React Flux - wait for props before rendering child components
- Wait for function to complete before moving on
More Query from same tag
- how to close a popupState menu and call a function on same onClick
- Set state based on previous one in render function
- css-loader not importing .css file returning empty object
- In redux-observable - How can I dispatch an action "mid-stream" without returning the value of that action?
- Check if Contains in Array in React
- Why Nginx load balancer is not serving js/css files from nginx nodes?
- How to call a function from a function both residing on a React Component
- Incorrect value shown when calling parent function from child Reactjs
- How to filter both date and time together from list using reactjs
- React: update component's props from outside of render method without using state
- How to use a database value in manifest.json
- How do I set the default value of a <select> element in React?
- Reach router redirect on successful login
- showing details of a record using ReactJS
- Specify multiple reversed criteria for grid
- Redux Connect w/ HOC - TypeError: Cannot set property 'props' of undefined
- JEST testing of a Sagas call
- ionic react type is not assignable
- Understanding of how to use mapDispatchToProps in react-redux?
- How to update button width without css ReactJs
- Serving a static html page from a single page react app with react router
- Props "undefined" within useEffect
- React can't get response body from PHP API
- Telegram authorization without default button
- Transform .jsx string to .js
- React useEffect trigger conditionally
- Call multiple `setState` hooks from multiple successive async calls in a for loop
- Cannot destructure property 'history' of 'undefined' as it is undefined. --React.js
- Compare two Objects and determine the parent node of differed properties
- Micro frontend application