DEV Community

Cover image for Submitting a form in Nextjs 14 with onBlur, server actions, and validation

Submitting a form in Nextjs 14 with onBlur, server actions, and validation

Bryan Smith on February 07, 2024

Want a straightforward article on submitting a form in Nextjs to a server action using an HTML event onBlur? And with form validation? Then this i...
Collapse
 
leandro_nnz profile image
Leandro Nuñez

Hi. Thanks for sharing. I have a couple of questions:

  • Why would you use onBlur instead of onChange? onBlur is going to be called every time you move away from the input.
  • Why would you execute the same logic as the form submission logic every time the onBlur happens?

Thanks!

Collapse
 
nathanburgess profile image
Nathan Burgess
  • onChange would call the formAction every single keystroke, which isn't very efficient. onBlur will persist the data once the change is complete.
  • That's the entire point of this post: to submit data onBlur, so that the users' data is saved without requiring them hitting a save button
Collapse
 
leandro_nnz profile image
Leandro Nuñez

I see.

  • What would be a use-case of this pattern?
  • what happens if the user changes the input value, navigates to other page before the async operation finished? Thanks in advance. Sorry for the trouble.
Thread Thread
 
orionseven profile image
Bryan Smith

I have a form where I need to capture the users interaction immediately. It's during signup and I don't want any save buttons and don't want any lost data. It can be inefficient, but it's a limited case and the payoff for less friction is worth it.

In my use case the user can't advance to another page, they're mid onboarding. But if that could be the case you'd need to handle the outcomes.

Collapse
 
truemanishtiwari profile image
Manish Tiwari

grtgrtg