iway1 / react-ts-form

https://react-ts-form.com
MIT License
2.01k stars 33 forks source link

Feature - Add "Hidden Values" #83

Open iway1 opened 1 year ago

iway1 commented 1 year ago

If we could pass hidden values as a prop to the form component, it would make it viable to share most if not all form schemas with trpc-like backends which could make synchronization between front end and backend very easy in cases where the backend is using zod schemas for input.

For example, imagine we had a "comment" form that created a comment for a post. The form only needs to include a text field in the UI, but the backend expects both the text of the comment and the ID of the post:

export const MyCommentSchema = z.object({
  text: z.string(),
  postId: z.string(),
})
import { MyCommentSchema } from 'schema'; // import schema from shared package / file
// trpc router
const trpcRouter = t.router({
  postComment: z.procedure.input(MyCommentSchema).mutation(/* do stuff */)
})

In our next.js page for example:

import { MyCommentSchema } from 'schema'; // import schema from shared package / file
// front end

const MyPage = ()=>{
  const mutation = api.postComment.useMutation()
  const {query: {postId}} = useRouter()
  return (
    <Form 
      schema={MyCommentSchema}
      onSubmit={mutation.mutate}
      hiddenValues={{
        postId: postId,
      }}
    />
  )
}

No component would be rendered for the postId field (since we don't want users to have to input hidden values), and the hidden value would get passed to the onSubmit callback.

Any additional changes to our shared schema would both add the field to the input of the trpc router, and also render a new field on the frontend. Enables fullstack typesafe form submission with a single source of truth.

tonoli commented 4 months ago

This could be very nice!