Skip to content

feat (form-core): Merging Form-level server errors with Field-level errors #1432

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 7 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
10 changes: 7 additions & 3 deletions examples/react/next-server-actions/src/app/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,13 @@ import { formOpts } from './shared-code'
const serverValidate = createServerValidate({
...formOpts,
onServerValidate: ({ value }) => {
if (value.age < 12) {
return 'Server validation: You must be at least 12 to sign up'
}
if (value.age < 12)
return {
fields: {
age: 'Server validation: You must be at least 12 to sign up',
},
form: 'Form level Error: Age must be at least 12',
}
},
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import { useActionState } from 'react'
import { mergeForm, useForm, useTransform } from '@tanstack/react-form'
import { initialFormState } from '@tanstack/react-form/nextjs'
import { useStore } from '@tanstack/react-store'
import someAction from './action'
import { formOpts } from './shared-code'

Expand All @@ -18,14 +17,8 @@ export const ClientComp = () => {
),
})

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

return (
<form action={action as never} onSubmit={() => form.handleSubmit()}>
{formErrors.map((error) => (
<p key={error as unknown as string}>{error}</p>
))}

<form.Field
name="age"
validators={{
Expand Down
1 change: 0 additions & 1 deletion examples/react/next-server-actions/src/app/shared-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { formOptions } from '@tanstack/react-form/nextjs'

export const formOpts = formOptions({
defaultValues: {
firstName: '',
age: 0,
},
})
44 changes: 44 additions & 0 deletions packages/form-core/src/FormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1130,6 +1130,35 @@
this.options.transform?.fn(newObj)
state = newObj.state
this.prevTransformArray = transformArray

const serverErrorMap = this.store.state.errorMap['onServer'] as

Check warning on line 1134 in packages/form-core/src/FormApi.ts

View check run for this annotation

Codecov / codecov/patch

packages/form-core/src/FormApi.ts#L1134

Added line #L1134 was not covered by tests
| Record<string, string>
| undefined

if (!serverErrorMap) return state

batch(() => {
void (Object.values(this.fieldInfo) as FieldInfo<any>[]).forEach(
(field) => {
const fieldInstance = field.instance

Check warning on line 1143 in packages/form-core/src/FormApi.ts

View check run for this annotation

Codecov / codecov/patch

packages/form-core/src/FormApi.ts#L1140-L1143

Added lines #L1140 - L1143 were not covered by tests

if (!fieldInstance) return

if (fieldInstance.name in serverErrorMap) {
fieldInstance.setMeta((prev) => ({

Check warning on line 1148 in packages/form-core/src/FormApi.ts

View check run for this annotation

Codecov / codecov/patch

packages/form-core/src/FormApi.ts#L1148

Added line #L1148 was not covered by tests
...prev,
errorMap: {
...prev.errorMap,
onServer: serverErrorMap[fieldInstance.name],
},
}))
fieldInstance.mount()

Check warning on line 1155 in packages/form-core/src/FormApi.ts

View check run for this annotation

Codecov / codecov/patch

packages/form-core/src/FormApi.ts#L1155

Added line #L1155 was not covered by tests
}

this.validateField(fieldInstance.name, 'server')

Check warning on line 1158 in packages/form-core/src/FormApi.ts

View check run for this annotation

Codecov / codecov/patch

packages/form-core/src/FormApi.ts#L1158

Added line #L1158 was not covered by tests
},
)
})
}

return state
Expand Down Expand Up @@ -1503,6 +1532,20 @@
},
}))
}

/**
* when we have an error for onServer in the state, we want
* to clear the error as soon as the user changes the value in the field
*/
if (cause !== 'server') {
this.baseStore.setState((prev) => ({
...prev,
errorMap: {
...prev.errorMap,
onServer: undefined,
},
}))
}
})

return { hasErrored, fieldsErrorMap: currentValidationErrorMap }
Expand Down Expand Up @@ -1925,6 +1968,7 @@
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
...prev?.errorMap,
onMount: undefined,
onServer: undefined,
},
}))
}
Expand Down
35 changes: 28 additions & 7 deletions packages/react-form/src/nextjs/createServerValidate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,20 +96,41 @@
validationSource: 'form',
})) as UnwrapFormAsyncValidateOrFn<TOnServer> | undefined

console.log('ON SERVER ERROR', onServerError)

Check warning on line 99 in packages/react-form/src/nextjs/createServerValidate.ts

View check run for this annotation

Codecov / codecov/patch

packages/react-form/src/nextjs/createServerValidate.ts#L99

Added line #L99 was not covered by tests

if (!onServerError) return values

const onServerErrorVal = (
isGlobalFormValidationError(onServerError)
? onServerError.form
: onServerError
) as UnwrapFormAsyncValidateOrFn<TOnServer>
let onServerErrorVal = undefined
let onServerErrorValFields = undefined

Check warning on line 104 in packages/react-form/src/nextjs/createServerValidate.ts

View check run for this annotation

Codecov / codecov/patch

packages/react-form/src/nextjs/createServerValidate.ts#L103-L104

Added lines #L103 - L104 were not covered by tests

if (isGlobalFormValidationError(onServerError)) {
onServerErrorVal =

Check warning on line 107 in packages/react-form/src/nextjs/createServerValidate.ts

View check run for this annotation

Codecov / codecov/patch

packages/react-form/src/nextjs/createServerValidate.ts#L107

Added line #L107 was not covered by tests
onServerError.form as UnwrapFormAsyncValidateOrFn<TOnServer>
onServerErrorValFields =

Check warning on line 109 in packages/react-form/src/nextjs/createServerValidate.ts

View check run for this annotation

Codecov / codecov/patch

packages/react-form/src/nextjs/createServerValidate.ts#L109

Added line #L109 was not covered by tests
onServerError.fields as UnwrapFormAsyncValidateOrFn<TOnServer>
} else {
onServerErrorVal = onServerError as UnwrapFormAsyncValidateOrFn<TOnServer>

Check warning on line 112 in packages/react-form/src/nextjs/createServerValidate.ts

View check run for this annotation

Codecov / codecov/patch

packages/react-form/src/nextjs/createServerValidate.ts#L111-L112

Added lines #L111 - L112 were not covered by tests
}

// Extract string values from errors if they're in object format
const errorsArray = onServerErrorVal
? Array.isArray(onServerErrorVal)
? onServerErrorVal.map((err) =>

Check warning on line 118 in packages/react-form/src/nextjs/createServerValidate.ts

View check run for this annotation

Codecov / codecov/patch

packages/react-form/src/nextjs/createServerValidate.ts#L117-L118

Added lines #L117 - L118 were not covered by tests
typeof err === 'object' ? Object.values(err)[0] : err,
)
: [

Check warning on line 121 in packages/react-form/src/nextjs/createServerValidate.ts

View check run for this annotation

Codecov / codecov/patch

packages/react-form/src/nextjs/createServerValidate.ts#L121

Added line #L121 was not covered by tests
typeof onServerErrorVal === 'object'
? Object.values(onServerErrorVal)[0]
: onServerErrorVal,

Check warning on line 124 in packages/react-form/src/nextjs/createServerValidate.ts

View check run for this annotation

Codecov / codecov/patch

packages/react-form/src/nextjs/createServerValidate.ts#L123-L124

Added lines #L123 - L124 were not covered by tests
]
: []

Check warning on line 126 in packages/react-form/src/nextjs/createServerValidate.ts

View check run for this annotation

Codecov / codecov/patch

packages/react-form/src/nextjs/createServerValidate.ts#L126

Added line #L126 was not covered by tests

const formState: ServerFormState<TFormData, TOnServer> = {
errorMap: {
onServer: onServerError,
onServer: onServerErrorValFields,
},
values,
errors: onServerErrorVal ? [onServerErrorVal] : [],
errors: errorsArray,
}

throw new ServerValidateError({
Expand Down