diff --git a/packages/svelte-form/src/createForm.svelte.ts b/packages/svelte-form/src/createForm.svelte.ts index 1b40ce748f..bf75b4a96c 100644 --- a/packages/svelte-form/src/createForm.svelte.ts +++ b/packages/svelte-form/src/createForm.svelte.ts @@ -1,6 +1,19 @@ import { FormApi } from '@tanstack/form-core' import { useSelector } from '@tanstack/svelte-store' -import { onMount } from 'svelte' +import { getContext, hasContext, onMount, setContext } from 'svelte' + +const FORM_ID_CTX = Symbol() + +function nextFormId(): string { + try { + if (!hasContext(FORM_ID_CTX)) setContext(FORM_ID_CTX, { n: 0 }) + const ctx = getContext<{ n: number }>(FORM_ID_CTX) + return `svelte-form-${++ctx.n}` + } catch { + // Outside component context (unit tests, etc.) + return `svelte-form-${Math.random().toString(36).slice(2, 9)}` + } +} import Field from './Field.svelte' import FormGroup from './FormGroup.svelte' import Subscribe from './Subscribe.svelte' @@ -310,7 +323,7 @@ export function createForm< TFormOnDynamicAsync, TFormOnServer, TSubmitMeta - >(options) + >({ ...options, formId: options?.formId ?? nextFormId() } as typeof options) const extendedApi: typeof api & SvelteFormApi< TParentData,