Next.js Discord

Discord Forum

Form Submit Not Following Logic

Unanswered
Asian paper wasp posted this in #help-forum
Open in Discord
Asian paper waspOP
We've got a new project using the page router with Next v13.4.13. We are also using class components.

The form submit handler is pretty basic.
private async submitFormHandler() {
  console.log('submitFormHandler: BEGIN');
  const data = {
    firstName: 'string',
    lastName: 'string',
    email: 'string'
  };
  console.log('form data\n', data);
  return data;
}

When the form is submitted, the submitFormHandler doesn't fire because the page reloads immediately. We can identify this by the console.log() not firing.

Our several types of event.preventDefault() aren't working either.
<button
    type='submit'
    onSubmit={() => this.submitFormHandler()}
>
    Submit
</button>

When the page reloads, all of the form fields are added as URL parameters.
http://localhost:3000/?firstName=asdf&lastNameasdf=&email=asdf

6 Replies

Asian paper waspOP
We have several Next apps. This is the only one using Tailwind UI, and the only one showing this problem.
It's default behaviour of browsers, you have to call event.preventDefault() to prevent the redirect.
there is no onsubmit event on buttons, only in the form element. a button with type="submit will call the onsubmit in the form itself so you need to move your logic there
Steps to resolve:
// 1. submit event moved to <form>
<form onSubmit={() => this.submitFormHandler()}></form>
// 2. event variable passed into on submit method
<form onSubmit={(event) => this.submitFormHandler(event)}></form>
// 3. event type setup on form handler method
private async submitFormHandler(event: React.FormEvent<HTMLFormElement>) {}

Now, event.preventDefault() is working as expected.