TanStack / form

🤖 Powerful and type-safe form state management for the web. TS/JS, React Form, Solid Form, Lit Form and Vue Form.
https://tanstack.com/form
MIT License
3.74k stars 338 forks source link

[FEATURE] Form callback API #989

Open crutchcorn opened 3 days ago

crutchcorn commented 3 days ago

Imagine a usecase where the user wants two buttons, they both send the item to the backend (after form validation) but one goes back to the list and the other goes to a different page, like a step 2 or a detail page.

To solve this, we're thinking of introducing a new API called onSubmitMeta that allows you to pass arguments to the onSubmit function via a meta field.

This API might look something like this:

  const form = useForm({
    defaultValues: {
      firstName: '',
      lastName: '',
    },
    // Is 'never' by default unless you provide a type
    // {} is the default value passed to `onSubmit`'s `meta` property
    onSubmitMeta: {} as { someValue: string },
    onSubmit: async ({ value, meta }) => {
      // Do something with form data
      console.log(value)
      // Do something with the values passed via handleSubmit
      console.log(meta)
    },
  })

  return (
    <div>
      <h1>Simple Form Example</h1>
      <form
        onSubmit={(e) => {
          e.preventDefault()
          e.stopPropagation()
          form.handleSubmit({
            someValue: 'value',
          })
        }}
      >

By having onSubmitMeta it enables us to have a few features on top of passing properties such as:

This API should be purely additive, so it may not make it into v1 of TanStack Form

thejasviES commented 3 days ago

Hi @crutchcorn can I be assigned this ticket?

zoodirector commented 1 day ago

Hey @crutchcorn . Thank you very much for taking up my ideas of #949 ! However, I don't find this API proposal of yours particularly advantageous. It would require me to put the business logic that handles the server response (e.g. navigating to different routes after submissions) inside the onSubmit function of the form. It is an inversion of control where not necessary. For me it would feel more natural if the form API would return control after the successful submission of the form and not wrap around the business logic that follows afterwards. I think that my suggested design in #949 would allow for a better decoupling of code. For example if I want to reuse the same redirection logic in different forms.

But that is just my opinion. I guess I could also live with the API suggested above.