TanStackT
TanStack7mo ago
5 replies
popular-magenta

Show API validations in the Form

I validate my forms on the backend, here's an example
{
    "json": {
        "defined": false,
        "code": "INPUT_VALIDATION_FAILED",
        "status": 422,
        "message": "INPUT_VALIDATION_FAILED",
        "data": {
            "errors": [],
            "properties": {
                "name": {
                    "errors": [
                        "Name must be at least 1 characters"
                    ]
                }
            }
        }
    }
}


Now I want to push the errors on the form, but I'm not sure which api to use

function RouteComponent() {
  const {
    data: {user},
  } = useSuspenseQuery(orpc.auth.getSession.queryOptions());

  const updateNameMutation = useMutation(
    orpc.user.updateName.mutationOptions({
      onSuccess: () => {
        queryClient.invalidateQueries(orpc.auth.getSession.queryOptions());
        toast.success("Your name has been updated");
      },
    }),
  );

  const form = useForm({
    defaultValues: {name: user?.name || ""},
    onSubmit: async ({value: {name}}) => {
      updateNameMutation.mutate({name});
    },
  });

return <div>...</div>
}
Was this page helpful?