Open History to see the last commit
1---
2id: async-initial-values
3title: Async Initial Values
4---
5
6Forms often edit data loaded from an API. A server-state library such as
7TanStack Query should own fetching, caching, loading, and retries; TanStack Form
8should own the editable copy.
9
10There are two supported ways to provide async initial values: wait to create the
11form until the data is ready, or create it immediately with complete fallback
12values. Choose the approach that best matches the loading experience your UI
13needs.
14
15## Wait for data before creating the editor
16
17Render a loading or error state first, then mount a component whose
18`defaultValues` are complete.
19
20```svelte
21<!-- UserPage.svelte -->
22<script lang="ts">
23 import { createQuery } from '@tanstack/svelte-query'
24 import { derived, toStore } from 'svelte/store'
25 import UserEditor from './UserEditor.svelte'
26 import type { User } from './types.js'
27
28 const { userId }: { userId: string } = $props()
29 const userIdStore = toStore(() => userId)
30 const userQuery = createQuery(
31 derived(userIdStore, (currentUserId) => ({
32 queryKey: ['user', currentUserId],
33 queryFn: async (): Promise<User> => {
34 const response = await fetch(`/api/users/${currentUserId}`)
35 return response.json()
36 },
37 })),
38 )
39</script>
40
41{#if $userQuery.isPending}
42 <p>Loading…</p>
43{:else if $userQuery.isError}
44 <p role="alert">Could not load the user.</p>
45{:else}
46 {#key userId}
47 <UserEditor user={$userQuery.data} />
48 {/key}
49{/if}
50```
51
52```svelte
53<!-- UserEditor.svelte -->
54<script lang="ts">
55 import { createForm } from '@tanstack/svelte-form'
56 import type { User } from './types.js'
57
58 const { user }: { user: User } = $props()
59 const form = createForm(() => ({
60 defaultValues: user,
61 onSubmit: async ({ value }) => {
62 await fetch('/api/users', {
63 method: 'PUT',
64 headers: { 'content-type': 'application/json' },
65 body: JSON.stringify(value),
66 })
67 },
68 }))
69</script>
70
71<form
72 onsubmit={(event) => {
73 event.preventDefault()
74 form.handleSubmit()
75 }}
76>
77 <!-- fields -->
78</form>
79```
80
81This pattern is useful when no form state is needed during loading. Mounting the
82editor only after data exists also makes it explicit when switching records
83should create a fresh form. The keyed block recreates the editor when `userId`
84changes.
85
86## Create the form before data arrives
87
88You can instead call `createForm` in the same component as `createQuery`.
89Provide a static, shape-complete fallback so `defaultValues` are never
90`undefined`.
91
92```svelte
93<script lang="ts">
94 import { createForm } from '@tanstack/svelte-form'
95 import { createQuery } from '@tanstack/svelte-query'
96 import { derived, toStore } from 'svelte/store'
97 import type { User } from './types.js'
98
99 const { userId }: { userId: string } = $props()
100 const emptyUser: User = {
101 firstName: '',
102 lastName: '',
103 }
104
105 const userIdStore = toStore(() => userId)
106 const userQuery = createQuery(
107 derived(userIdStore, (currentUserId) => ({
108 queryKey: ['user', currentUserId],
109 queryFn: async (): Promise<User> => {
110 const response = await fetch(`/api/users/${currentUserId}`)
111 return response.json()
112 },
113 })),
114 )
115
116 const form = createForm(() => ({
117 defaultValues: $userQuery.data ?? emptyUser,
118 onSubmit: async ({ value }) => {
119 await fetch('/api/users', {
120 method: 'PUT',
121 headers: { 'content-type': 'application/json' },
122 body: JSON.stringify(value),
123 })
124 },
125 }))
126</script>
127
128{#if $userQuery.isPending}
129 <p>Loading…</p>
130{:else if $userQuery.isError}
131 <p role="alert">Could not load the user.</p>
132{:else}
133 <form
134 onsubmit={(event) => {
135 event.preventDefault()
136 form.handleSubmit()
137 }}
138 >
139 <!-- fields -->
140 </form>
141{/if}
142```
143
144Because `createForm` receives an options function, reading `$userQuery` inside
145that function keeps the options reactive. When the query data replaces the
146fallback, TanStack Form applies the new `defaultValues` to untouched fields
147while preserving fields the user has already touched.
148
149This is the approach demonstrated by the repository's
150`examples/svelte/query-integration` example.
151
152## Background refetches and record changes
153
154`defaultValues` establish the form's baseline; they are not a fully controlled
155`values` prop. In the fallback pattern, later `defaultValues` updates use the
156same touched-field-preserving behavior.
157
158If background refetches arrive while a user is editing, decide at the product
159level whether to keep local edits, prompt before replacing them, or call
160`form.reset(nextValues)` deliberately. Do not overwrite in-progress input merely
161because a query refreshed.
162
163When switching to a different record, either recreate a keyed editor as in the
164first pattern or deliberately reset the existing form. Otherwise, touched
165values from the previous record can be preserved when the new defaults arrive.