Giter Club home page Giter Club logo

Comments (8)

crutchcorn avatar crutchcorn commented on September 26, 2024

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.

benjavicente avatar benjavicente commented on September 26, 2024

The problem that I have with formFactory as the primitive to share code is that it holds mainly client code (useForm, useField, Field, validateFormDataand 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 with validatorAdapter) and server (that handles the FormData directly with onServerValidate and validatorAdapter). The only shared validation code seems to be validatorAdapter.
  • initialFormState is like the result of a validation step in this context (errorsMap and errors), 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.

crutchcorn avatar crutchcorn commented on September 26, 2024

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.

crutchcorn avatar crutchcorn commented on September 26, 2024

@benjavicente I just made a (currently WIP, but pretty decently far into the refactor) PR that addresses this here:

#734

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.

benjavicente avatar benjavicente commented on September 26, 2024

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.

fraubungle avatar fraubungle commented on September 26, 2024

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.

crutchcorn avatar crutchcorn commented on September 26, 2024

Please open a new discussion for more guidance on how to use SSR

from form.

fraubungle avatar fraubungle commented on September 26, 2024

Please open a new discussion for more guidance on how to use SSR

I have here #775

from form.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.