Skip to content
Source
Sign inSign up
TanStack/form

fix(svelte-form): use stable module-level counter for default formId #2430

Openokxint(GitHub profile, opens in a new tab)wants to merge 2 commits intomain fromrefs/pull/2430/headopened

Showing 1 changed file with 15 additions and 2 deletions.

x
0 of 1 viewed, 1 left
15 additions and 2 deletionspackages/svelte-form/src/createForm.svelte.tsModified
View file
@@ -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 @@
TFormOnDynamicAsync,
TFormOnServer,
TSubmitMeta
- >(options)
+ >({ ...options, formId: options?.formId ?? nextFormId() } as typeof options)
const extendedApi: typeof api &
SvelteFormApi<
TParentData,