Skip to content

feat(react-form): correctly handle client-side validation with NextJS server-action #1299

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { useActionState } from 'react'
import { mergeForm, useForm, useTransform } from '@tanstack/react-form'
import { initialFormState } from '@tanstack/react-form/nextjs'
import { initialFormState, useActionSubmit } from '@tanstack/react-form/nextjs'
import { useStore } from '@tanstack/react-store'
import someAction from './action'
import { formOpts } from './shared-code'
Expand All @@ -18,10 +18,11 @@ export const ClientComp = () => {
),
})

const onActionSubmit = useActionSubmit(form)
const formErrors = useStore(form.store, (formState) => formState.errors)

return (
<form action={action as never} onSubmit={() => form.handleSubmit()}>
<form action={action as never} onSubmit={onActionSubmit()}>
{formErrors.map((error) => (
<p key={error as unknown as string}>{error}</p>
))}
Expand Down
1 change: 1 addition & 0 deletions packages/react-form/src/nextjs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from '@tanstack/form-core'
export * from './createServerValidate'
export * from './error'
export * from './types'
export * from './useActionSubmit'
33 changes: 33 additions & 0 deletions packages/react-form/src/nextjs/useActionSubmit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { useCallback, useRef } from 'react'
import type { FormEventHandler } from 'react'
import type { FormApi } from '@tanstack/form-core'

export const useActionSubmit = <TSubmitMeta>(
form: FormApi<any, any, any, any, any, any, any, any, any, TSubmitMeta>,
) => {
const isActionSubmittedRef = useRef(false)

const onActionSubmit = useCallback(
(submitMeta?: TSubmitMeta): FormEventHandler<HTMLFormElement> => {
return async (event) => {
if (isActionSubmittedRef.current) {
isActionSubmittedRef.current = false
return
}

event.preventDefault()

await new Promise((resolve) => setTimeout(resolve))
await (submitMeta ? form.handleSubmit(submitMeta) : form.handleSubmit())

if (form.state.isValid) {
isActionSubmittedRef.current = true
;(event.target as HTMLFormElement).requestSubmit()
}
}
},
[form],
)

return onActionSubmit
}
Loading