T
TanStack3mo ago
conscious-sapphire

Should I preventDefault with Next.js server actions?

I am using Next server actions, but I want to include client side validation that prevents submit if there are any errors. If I include e.preventDefault, nothing happens. If I exclude e.preventDefault, the post is always sent. When I try to type into the input again, it does not change the value until 2 characters are entered.
const [state, action] = useActionState(logExample, initialFormState);

const form = useForm({
...formOpts,
transform: useTransform((baseForm) => mergeForm(baseForm, state!), [state]),
validators: {
onChange: ({ value }) =>
value.text.trim().length === 0 && { fields: { text: 'Required' } },
},
});

<form
action={action}
onSubmit={(e) => {
// e.preventDefault();
form.handleSubmit();
}}
>
...
</form>
const [state, action] = useActionState(logExample, initialFormState);

const form = useForm({
...formOpts,
transform: useTransform((baseForm) => mergeForm(baseForm, state!), [state]),
validators: {
onChange: ({ value }) =>
value.text.trim().length === 0 && { fields: { text: 'Required' } },
},
});

<form
action={action}
onSubmit={(e) => {
// e.preventDefault();
form.handleSubmit();
}}
>
...
</form>
How do I prevent submit on validation errors? How do I get input to trigger the change event after an invalid submit attempt? Example here: https://stackblitz.com/edit/nextjs-dbp2u3qq?file=app%2Fexample-form.tsx
StackBlitz
Nextjs (duplicated) - StackBlitz
The React framework for production.
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?