From b16d6c723024f304e48641633fd0e3fb12e7c784 Mon Sep 17 00:00:00 2001 From: Leonardo Montini Date: Wed, 2 Oct 2024 16:50:42 +0200 Subject: [PATCH] docs: await async submit operations to showcase isSubmitting flag (#965) * docs: await mutation to showcase isSubmitting flag * docs: improve isSubmitting docs --- examples/react/query-integration/src/index.tsx | 11 ++++++++++- packages/form-core/src/FormApi.ts | 11 ++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/examples/react/query-integration/src/index.tsx b/examples/react/query-integration/src/index.tsx index e6eaa0d64..6b6f07714 100644 --- a/examples/react/query-integration/src/index.tsx +++ b/examples/react/query-integration/src/index.tsx @@ -4,6 +4,7 @@ import { useForm } from '@tanstack/react-form' import { QueryClient, QueryClientProvider, + useMutation, useQuery, } from '@tanstack/react-query' import type { FieldApi } from '@tanstack/react-form' @@ -28,6 +29,14 @@ export default function App() { }, }) + const saveUserMutation = useMutation({ + mutationFn: async (value: { firstName: string; lastName: string }) => { + await new Promise((resolve) => setTimeout(resolve, 1000)) + console.log(value) + return value + }, + }) + const form = useForm({ defaultValues: { firstName: data?.firstName ?? '', @@ -35,7 +44,7 @@ export default function App() { }, onSubmit: async ({ value }) => { // Do something with form data - console.log(value) + await saveUserMutation.mutateAsync(value) }, }) diff --git a/packages/form-core/src/FormApi.ts b/packages/form-core/src/FormApi.ts index b618efcfb..db6a0cc72 100644 --- a/packages/form-core/src/FormApi.ts +++ b/packages/form-core/src/FormApi.ts @@ -254,7 +254,16 @@ export type FormState = { */ isFieldsValid: boolean /** - * A boolean indicating if the form is currently submitting. + * A boolean indicating if the form is currently in the process of being submitted after `handleSubmit` is called. + * + * Goes back to `false` when submission completes for one of the following reasons: + * - the validation step returned errors. + * - the `onSubmit` function has completed. + * + * Note: if you're running async operations in your `onSubmit` function make sure to await them to ensure `isSubmitting` is set to `false` only when the async operation completes. + * + * This is useful for displaying loading indicators or disabling form inputs during submission. + * */ isSubmitting: boolean /**