skip to Main Content

I’ve been toying around with the NextJS starter example mentioned in this course and I was wondering what would be the proper way to prevent users from submitting a form by pressing the enter key when the server action is running/pending.
There are examples in NextJS’s docs of using the useFormStatus hook to disable the submit button, but the form still can be submitted with the enter key, duplicating the request to the server/db.

I know this seems like a very basic interaction, but I haven’t been able to find much information about it. What would be the best practice here? Wrapping the server action with a useTransition hook? Debouncing the action?

Thank you in advance!

The sample form is very simple, it just takes three values and inserts them in the db.

export default function Page() {
  async function createInvoice(formData: FormData) {
    'use server'
 
    const rawFormData = {
      customerId: formData.get('customerId'),
      amount: formData.get('amount'),
      status: formData.get('status'),
    }
 
    // mutate data
    // revalidate cache
  }
 
  return
    <form action={createInvoice}>
      ...
      <SubmitButton /> // uses useFormStatus to disable the button while the action is pending
    </form>
}

2

Answers


  1. Since your form has multiple input elements, the best way to disable submit on pressing the enter key is by using e.preventDefault() for onSubmit.

    <form onSubmit={this.submitHandler}>
    
    submitHandler(e) {
        e.preventDefault();
    }
    
    Login or Signup to reply.
  2. How about using the form status and the onSubmit prop of the form to prevent a new submission if it already submitting.

    import { useFormStatus } from 'react-dom'
    
    export default function Page() {
      const { pending } = useFormStatus()
    
      async function createInvoice(formData: FormData) {
        'use server'
    
        const rawFormData = {
          customerId: formData.get('customerId'),
          amount: formData.get('amount'),
          status: formData.get('status'),
        }
    
        // mutate data
        // revalidate cache
      }
    
      return
        <form onSubmit={pending ? (event) => { event.preventDefault(); } : undefined} action={createInvoice}>
          ...
          <SubmitButton /> // uses useFormStatus to disable the button while the action is pending
        </form>
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search