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```tsx
21// UserPage.tsx
22import { Show } from 'solid-js'
23import { createQuery } from '@tanstack/solid-query'
24import { UserEditor } from './UserEditor'
25import type { User } from './types'
26
27export function UserPage(props: { userId: string }) {
28 const userQuery = createQuery(() => ({
29 queryKey: ['user', props.userId],
30 queryFn: async (): Promise<User> => {
31 const response = await fetch(`/api/users/${props.userId}`)
32 return response.json()
33 },
34 }))
35
36 return (
37 <Show
38 when={!userQuery.isError}
39 fallback={<p role="alert">Could not load the user.</p>}
40 >
41 <Show when={userQuery.data} keyed fallback={<p>Loading…</p>}>
42 {(user) => <UserEditor user={user} />}
43 </Show>
44 </Show>
45 )
46}
47```
48
49```tsx
50// UserEditor.tsx
51import { createForm } from '@tanstack/solid-form'
52import type { User } from './types'
53
54export function UserEditor(props: { user: User }) {
55 const form = createForm(() => ({
56 defaultValues: props.user,
57 onSubmit: async ({ value }) => {
58 await fetch('/api/users', {
59 method: 'PUT',
60 headers: { 'content-type': 'application/json' },
61 body: JSON.stringify(value),
62 })
63 },
64 }))
65
66 return (
67 <form
68 onSubmit={(event) => {
69 event.preventDefault()
70 form.handleSubmit()
71 }}
72 >
73 {/* fields */}
74 </form>
75 )
76}
77```
78
79This pattern is useful when no form state is needed during loading. The keyed
80`Show` recreates the editor when a different user object arrives.
81
82## Create the form before data arrives
83
84You can instead call `createForm` in the same component as `createQuery`.
85Provide a static, shape-complete fallback so `defaultValues` are never
86`undefined`.
87
88```tsx
89import { Show } from 'solid-js'
90import { createQuery } from '@tanstack/solid-query'
91import { createForm } from '@tanstack/solid-form'
92import type { User } from './types'
93
94const emptyUser: User = {
95 firstName: '',
96 lastName: '',
97}
98
99export function UserPage(props: { userId: string }) {
100 const userQuery = createQuery(() => ({
101 queryKey: ['user', props.userId],
102 queryFn: async (): Promise<User> => {
103 const response = await fetch(`/api/users/${props.userId}`)
104 return response.json()
105 },
106 }))
107
108 const form = createForm(() => ({
109 defaultValues: userQuery.data ?? emptyUser,
110 onSubmit: async ({ value }) => {
111 await fetch('/api/users', {
112 method: 'PUT',
113 headers: { 'content-type': 'application/json' },
114 body: JSON.stringify(value),
115 })
116 },
117 }))
118
119 return (
120 <Show
121 when={!userQuery.isError}
122 fallback={<p role="alert">Could not load the user.</p>}
123 >
124 <Show when={!userQuery.isPending} fallback={<p>Loading…</p>}>
125 <form
126 onSubmit={(event) => {
127 event.preventDefault()
128 form.handleSubmit()
129 }}
130 >
131 {/* fields */}
132 </form>
133 </Show>
134 </Show>
135 )
136}
137```
138
139Because both integrations receive accessors, reading `userQuery.data` inside
140the form options accessor keeps the options reactive. When query data replaces
141the fallback, TanStack Form applies the new `defaultValues` to untouched fields
142while preserving fields the user has already touched.
143
144This is the approach demonstrated by the repository's
145`examples/solid/query-integration` example.
146
147## Background refetches and record changes
148
149`defaultValues` establish the form's baseline; they are not a fully controlled
150`values` prop. In the fallback pattern, later `defaultValues` updates use the
151same touched-field-preserving behavior.
152
153If background refetches arrive while a user is editing, decide at the product
154level whether to keep local edits, prompt before replacing them, or call
155`form.reset(nextValues)` deliberately. Do not overwrite in-progress input merely
156because a query refreshed.
157
158When switching to a different record, either recreate a keyed editor as in the
159first pattern or deliberately reset the existing form. Otherwise, touched
160values from the previous record can be preserved when the new defaults arrive.