Reputation: 4010
I have a single React component that looks something like this:
var SendFormToServer = React.createClass({
propTypes: {
Values: React.PropTypes.object,
getValues: React.PropTypes.func,
sendToServer: React.PropTypes.func
},
getInitialState: function () {
return {
Values: this.props.Values
};
},
handleClick: function (e) {
var scope = this.props.getValues();
this.setState({ Values: scope });
this.forceUpdate();
this.props.sendToServer(e);
},
render: function () {
return (
<div className="pull-right">
<div id="model" style={{"display": "none"}}>
company = '{this.state.Values.Company}'{newLine}
user = '{this.state.Values.User}'{newLine}
notes = '{this.state.Values.Notes}'{newLine}
</div>
<input type="button" className="btn btn-success" onClick={this.handleClick} value="Submit" />
</div>
);
}
});
The problem is.. is that the re-rendering occurs AFTER the handleClick() is finished. It doesn't occur after this.setState as many people mentioned on stackoverflow, and it doesn't even occur after this.forceUpdate().
I need the rerendering to occur before this.props.sendToServer function gets called. Is there a way to do this? Or do I have to come up with a different solution?
Upvotes: 2
Views: 125
Reputation: 8065
this.setState()
and this.forceUpdate()
are asynchronous functions so they don't update immediately. However what you can do is pass your next function as a callback to setState
like this:
this.setState({ Values: scope }, () => {
this.props.sendToServer(e);
});
Upvotes: 3
Reputation: 7209
The solution here involves realizing, first of all, that this.setState
will cause an update already. If you want to make that second call synchronously, you'd put it in the callback:
this.setState({ Values: scope }, () => this.props.sendToServer(e));
That should take care of it.
Upvotes: 2