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

async-initial-values.md

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