Skip to content
Source
Sign inSign up
TanStack/form

[FEATURE] Form callback API #989

Send to my agent
Closedcrutchcorn(GitHub profile, opens in a new tab) opened this issue 7 comments

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:

  • Type safety
  • Default arguments to meta field from the FW itself

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

  1. crutchcorn(GitHub profile, opens in a new tab) added labelstype: enhancement

  2. crutchcorn(GitHub profile, opens in a new tab) added labelsgood first issue

  3. Hi @crutchcorn can I be assigned this ticket?

  4. 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.

  5. I've got this exact use case, and I was able to solve it by looking at the id of the submitting button.

    () => {
      let form = useForm({
        defaultValues: {},
        onSubmit: async ({ value }) => await post(value),
      });
      return (
        <form
          onSubmit={async (event) => {
            event.preventDefault();
            event.stopPropagation();
            await form.handleSubmit();
            if (event.nativeEvent.submitter.id === "save-and-go-back") {
              // redirect
            }
          }}
        >
          <button id="save" name="save" type="submit">
            Save
          </button>
          <button id="save-and-go-back" name="save-and-go-back" type="submit">
            Save & Go Back
          </button>
        </form>
      );
    };
    

    What I would love, is the ability to get the response returned from my onSubmit, from form.handleSubmit as @zoodirector has proposed above. Like this . That way, I could use some server values in the redirect (such as a newly created id).

    So it would become

    () => {
      let form = useForm({
        defaultValues: {},
        onSubmit: async ({ value }) => await post(value),
      });
      return (
        <form
          onSubmit={async (event) => {
            event.preventDefault();
            event.stopPropagation();
            const response = await form.handleSubmit();
            if (event.nativeEvent.submitter.id === "save-and-go-back") {
              history.push(`items/${response.id}`)
            }
          }}
        >
          <button id="save" name="save" type="submit">
            Save
          </button>
          <button id="save-and-go-back" name="save-and-go-back" type="submit">
            Save & Go Back
          </button>
        </form>
      );
    };
    
  6. I think there's value in getting the result from onSubmit but I also see not wanting to deal with unhandled promise rejections when calling handleSubmit.

    One possibility would be to move closer to the useMutation hook from TanStack Query where there are separate mutation.mutate and mutation.mutateAsync methods. The form object could have both submit and submitAsync methods which return void and the result of onSubmit respectively.

  7. @zoodirector, can you help me understand (in psuedo-code) what a real-world example of what you'd want to build is?

    I'm still not seeing the differences between your suggestion and our design here with the exception of typesafety

  8. Hi @crutchcorn I have illustrated how I would use my suggested API here: https://github.com/zoodirector/tanstack-form/blob/25b28ba5f2304fe59c9fcbf8cb4dd4f3312879ea/examples/react/handle-submit-results/src/index.tsx#L124

    There are two <button> components that proceed differently. One goes to the list view, the other goes to the detail view of the newly created item. Therefore it requires the result.id which is returned by form.handleSubmit.

    Is such an example what you were looking for?

    P.S. I like the suggestion of @Rinaldo with the backwards compatible way of having a handleSubmit and a new handleSubmitAsync.

  9. This issue is now resolved with the introduction of the OP API design. The suggestion to handle return types is to move code out of the field and into the form's onSubmit itself, passing meta props as-needed.

Sign in to join this conversation.