CrazyCSGuy
CrazyCSGuy

Reputation: 143

React Form is re-rendering on submit button before submitting form results

In my React application, I have a form in parent component and this form renders a form page from several pages(child components) depending an a value that I have. (Ex: if value = 1, show parent sign up page, if value = 2, show child sign up page etc.)

<form onSubmit={this.handleSubmit}
...
    <Button type = "submit" onClick={this.renderNewPage}</Button>
</form>

handleSubmit = e =>{
    const {ParentName, ChildName, ..., Country} = this.state;
    //checking before sending to backend
    console.log(ParentName);
    console.log(ChildName);
    ....
}

This submit button is clicked, the Form goes to "Thank you for signing up" page through renderNewPage()

The problem is towards the end of form, when I click submit button, the onClick is being triggered first before form's onSubmit attribute. So the form goes to new page before printing form info to console

My take on this is onClick={this.renderNewPage} is being called before onSubmit={this.handleSubmit}. Is there a way that I can put renderNewPage() on hold(or delay) until handleSubmit() is finished?

My react app is several 100's lines so I'm only posting important parts(I think) that are related to question. If the code above does not contain enough information, please let me know and I'll try to provide more.

Upvotes: 0

Views: 476

Answers (1)

Pavlos Karalis
Pavlos Karalis

Reputation: 2966

Yes the click is firing first; you can wrap renderNewPage's content in a setTimeout

renderNewPage = () => {
 setTimeout(()=>{
  //your code
 },0)
}

Depending on what either function does, the console log may be a brief flash.

Upvotes: 1

Related Questions