Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

async-initial-values.md

118 lines3.8 KB

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
21import { useQuery } from '@tanstack/react-query'
22import { useForm } from '@tanstack/react-form'
23​
24type User = {
25 firstName: string
26 lastName: string
28​
29export function UserPage({ userId }: { userId: string }) {
30 const userQuery = useQuery({
31 queryKey: ['user', userId],
32 queryFn: () => fetch(`/api/users/${userId}`).then((res) => res.json()),
33 })
34​
35 if (userQuery.isPending) return <p>Loading…</p>
36 if (userQuery.isError) return <p role="alert">Could not load the user.</p>
37​
38 return <UserEditor key={userId} user={userQuery.data} />
40​
41function UserEditor({ user }: { user: User }) {
42 const form = useForm({
43 defaultValues: user,
44 onSubmit: async ({ value }) => {
45 await fetch('/api/users', {
46 method: 'PUT',
47 headers: { 'content-type': 'application/json' },
48 body: JSON.stringify(value),
49 })
50 },
51 })
52​
53 return <form>{/* fields */}</form>
55```
56​
57This pattern is useful when no form state is needed during loading. Mounting the
58editor only after data exists also makes it explicit when switching records
59should create a fresh form.
60​
61## Create the form before data arrives
62​
63You can instead call `useForm` in the same component as `useQuery`. Provide a
64static, shape-complete fallback so `defaultValues` are never `undefined`.
65​
66```tsx
67const emptyUser: User = {
68 firstName: '',
69 lastName: '',
71​
72export function UserPage({ userId }: { userId: string }) {
73 const userQuery = useQuery({
74 queryKey: ['user', userId],
75 queryFn: () => fetch(`/api/users/${userId}`).then((res) => res.json()),
76 })
77​
78 const form = useForm({
79 defaultValues: userQuery.data ?? emptyUser,
80 onSubmit: async ({ value }) => {
81 await fetch('/api/users', {
82 method: 'PUT',
83 headers: { 'content-type': 'application/json' },
84 body: JSON.stringify(value),
85 })
86 },
87 })
88​
89 if (userQuery.isPending) return <p>Loading…</p>
90 if (userQuery.isError) return <p role="alert">Could not load the user.</p>
91​
92 return <form>{/* fields */}</form>
94```
95​
96When the query data replaces the fallback, TanStack Form applies the new
97`defaultValues` to untouched fields while preserving fields the user has
98already touched. In this example, the fields remain unmounted during loading,
99so the user cannot edit them before the loaded values arrive. You can also
100render the empty form immediately when that better suits the UI.
101​
102This is the approach demonstrated by the repository's
103`examples/react/query-integration` example.
104​
105## Background refetches and record changes
106​
107`defaultValues` establish the form's baseline; they are not a fully controlled
108`values` prop. In the fallback pattern, later `defaultValues` updates use the
109same touched-field-preserving behavior.
110​
111If background refetches arrive while a user is editing, decide at the product
112level whether to keep local edits, prompt before replacing them, or call
113`form.reset(nextValues)` deliberately. Do not overwrite in-progress input merely
114because a query refreshed.
115​
116When switching to a different record, either remount a keyed editor as in the
117first pattern or deliberately reset the existing form. Otherwise, touched
118values from the previous record can be preserved when the new defaults arrive.