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
Since your form has multiple input elements, the best way to disable submit on pressing the enter key is by using
e.preventDefault()
foronSubmit
.How about using the form status and the
onSubmit
prop of the form to prevent a new submission if it already submitting.