TanStackT
TanStack5mo ago
4 replies
foolish-indigo

How to use TanStack Start's `createServerFn`, validation library, & Form

I have a form that submits data to the server via TSS's
createServerFn
function:


const fooSchema = v.object({
  foo: v.string(),
});

export const doSomethingOnTheServer = createServerFn({ method: "POST" })
  .validator(fooSchema)
  .handler(async ({ data: foo }) => {
    return await doSomething(foo);
  });

const Form = () => {
  const updateFooMutation = useMutation({
    mutationFn: async (value: v.InferOutput<typeof fooSchema>) => {
      doSomethingOnTheServer({ data: value });
    },
  });

// implements createFormHook
  const fooForm = useAppForm({
    defaultValues: {
      foo: "bar",
    },
    validators: {
      onChange: fooSchema,
    },
    onSubmit: async ({ formApi, value }) => {
      await updateFooMutation.mutateAsync(value);

      formApi.reset();
    },
  });

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        e.stopPropagation();
        fooForm.handleSubmit();
      }}
    >
      <fooForm.AppField children={(field) => <field.TextField label="Foo" />} name="foo" />
    </form>
  );
};


Notice how the same schema is used in the validators.onChange field in the form and in the validator() function on the createServerFn chain.

I want to handle errors that come from the createServerFn().validator() function properly in the form. But from what I gather from the docs, I'm not doing this correctly. From what I can gather from the docs, what I'm supposed to do is to first validate the data inside validators.onSubmitAsync, and then the submit function will go through. https://tanstack.com/form/latest/docs/framework/react/guides/validation#setting-field-level-errors-from-the-forms-validators

Now if this is correct, I feel like this kind of wonky. I already have a validator on my server function that runs my validation on the server, and setting up another server function call to validate the data seems unnecessary. Is there a way to make this all play nice together?
At the core of TanStack Form's functionalities is the concept of validation. TanStack Form makes validation highly customizable: You can control when to perform the validation (on change, on input, on...
Form and Field Validation | TanStack Form React Docs
Was this page helpful?