Comments (8)
Oh, yikes, that's, uh, bad. Thank you for the report.
Could you make a PR adding a warning to our docs? Something akin to:
This feature is highly experimental and likely to change API as a result of backend code leaking to the frontend. We're currently investigating and will update this page as it comes.
As for form factory not being a good primitive to share code, what API would you alternatively propose? Keep in mind that it should/must infer the types of everything properly
from form.
The problem that I have with formFactory
as the primitive to share code is that it holds mainly client code (useForm
, useField
, Field
, validateFormData
and initialFormState
). The only relevant code that could share is validation logic and some default values. BUT:
- Validation (or parsing) is not really shared. Since validation is performed per input
<Field validators={...} />
instead of the complete form, there doesn't seem to be an easy way to share validation and parsing between client (code per field withvalidatorAdapter
) and server (that handles theFormData
directly withonServerValidate
andvalidatorAdapter
). The only shared validation code seems to bevalidatorAdapter
. initialFormState
is like the result of a validation step in this context (errorsMap
anderrors
), and not really relevant state that the server should consider before validation.
Also, .validateFormData
returns a partial of FormState
(that has .isTouched?
on the server 🧐) instead of something like a FormResult<T>
(code below) that correctly returns the validated (parsed) object with errorsMap
and errors
. This probably can be easily fixed.
type FormStaticState = { errors: ValidationError[], errorMap: ValidationErrorMap }
type FormResult<T> = { ok: true, values: T, formState: FormStaticState } | { ok: false, values: null, formState: FormStaticState }
Found https://conform.guide/integration/nextjs that I believe was better shared API between server and client, but not the granularity of this lib (it seems that it parses the entire FormData
to validate, to then re-render the entire component).
Site note: I tried to land to a great example of what a nicer server API could be, and in a break, i saw https://x.com/kentcdodds/status/1797439388064109020 too 😅. The examples on conform where to similar of what i had in mind.
from form.
Since validation is performed per input instead of the complete form
This is a misunderstanding of our library. We have both per field and whole form validation. As such, concerns about shared validation aren't quite right. You can easily use a schema for both client and server quite easily with Form today.
Can you share the example of what a good server/client API might look like in your view? Regardless of inspiration/etc?
Otherwise, I think we might make a minimal change to solve this problem.
from form.
@benjavicente I just made a (currently WIP, but pretty decently far into the refactor) PR that addresses this here:
Not only does it allow the API to match what I've outlined in that PR, it preserves the ability to do server & client schema validation all-in-one, like so:
// shared-code.ts
import { formOptions } from '@tanstack/react-form'
import { zodValidator } from '@tanstack/zod-form-adapter'
import { z } from 'zod'
export const schema = z.object({
age: z.number().min(12, 'You must be at least 12 to use this service'),
})
export const formOpts = formOptions({
defaultValues: {
firstName: '',
age: 0,
},
validatorAdapter: zodValidator,
validators: {
onChange: schema
}
})
// client-component.tsx
/* ... */
const form = useForm({
...formOpts,
transform: useTransform(
(baseForm: FormApi<any, any>) => mergeForm(baseForm, state),
[state],
),
})
/* ... */
// action.ts
'use server'
import { createServerValidate } from '@tanstack/react-form'
import { formOpts, schema } from './shared-code'
const serverValidate = createServerValidate({
...formOpts,
onServerValidate: schema
})
export default async function someAction(prev: unknown, formData: FormData) {
return await serverValidate(formData)
}
What do you think about this API? Thoughts?
from form.
It looks great, thanks!
The only thing that is unclear to me is how to use the validated data after serverValidate
, since it doesn't seem to be returned there. It might be better that serverValidate
returns the parsed values and the corresponding errors, and not directly what the client expects (similar of the return type of conform validation, where .reply()
is used to respond to an invalid form submission).
from form.
Hi sorry to necro this thread but the OP stated at the end
"that is unclear to me is how to use the validated data after serverValidate, since it doesn't seem to be returned there."
this is also the case for me, could you provide an example of how the data can be used after the validation?
a post to a database and a redirect, a simple console.log or aleart() would also help as a starting point.
from form.
Please open a new discussion for more guidance on how to use SSR
from form.
Please open a new discussion for more guidance on how to use SSR
I have here #775
from form.
Related Issues (20)
- Dependency Dashboard
- TypeError on validatorAdapter when passing form schema generic to useForm HOT 3
- errorMap is undefined in field's meta but the lib try to access it HOT 6
- form submit not trigger validators.onChangeAsync HOT 1
- Unable to display Validation Messages with Zod in Next.js HOT 5
- Zod field errors not populating for individual fields on form level validation HOT 7
- type error when using yup object schema fields HOT 1
- Array setFieldValue not behaving as expected.
- Type instantiation is excessively deep and possibly infinite on form.filed when using supabase generated types HOT 1
- `form.update` overwrites options instead of merging HOT 1
- ts error with useField: Type instantiation is excessively deep and possibly infinite HOT 3
- There is no easy or documented way to use `<button type="submit" name="...">` HOT 1
- "Type instantiation is excessively deep and possibly infinite" and tsc crashing HOT 6
- Image in README mistakenly mentions Svelte support HOT 1
- Data is not sent to the server (using Server Actions) if the input is disabled (disabled=true) HOT 1
- Accessing form error array using form.useStore and destructuring can cause react update depth issue
- Using both `onMount` and `onChange` validators on a field doesn't work HOT 4
- state.canSubmit value flickering with async validation HOT 1
- Component-level Suspense for Solid Form
- Form Validation Zod Type Error on Validators HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from form.