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 should own
7fetching, caching, loading, and retries; TanStack Form should own the editable
8copy.
9
10There are two supported approaches: wait to create the controller until the
11data is ready, or create it immediately with complete fallback values. Choose
12the one that matches the loading experience your element needs.
13
14## Wait before creating the editor
15
16Keep the controller optional, fetch the data, and create it only after complete
17defaults exist:
18
19```ts
20import { LitElement, html } from 'lit'
21import {
22 TanStackFormController,
23 formOptions,
24 type LitFormType,
25} from '@tanstack/lit-form'
26
27type User = {
28 firstName: string
29 lastName: string
30}
31
32const userFormShape = formOptions({
33 defaultValues: {
34 firstName: '',
35 lastName: '',
36 },
37})
38
39class UserEditor extends LitElement {
40 private form?: LitFormType<typeof userFormShape>
41 private loadError = false
42
43 connectedCallback() {
44 super.connectedCallback()
45 void this.loadUser()
46 }
47
48 private async loadUser() {
49 try {
50 const response = await fetch('/api/users/1')
51 const user = (await response.json()) as User
52
53 this.form = new TanStackFormController(this, {
54 defaultValues: user,
55 onSubmit: async ({ value }) => {
56 await fetch('/api/users/1', {
57 method: 'PUT',
58 headers: { 'content-type': 'application/json' },
59 body: JSON.stringify(value),
60 })
61 },
62 })
63 } catch {
64 this.loadError = true
65 }
66 this.requestUpdate()
67 }
68
69 render() {
70 if (this.loadError) return html`<p role="alert">Could not load.</p>`
71 if (!this.form) return html`<p>Loading…</p>`
72 return html`<form><!-- fields --></form>`
73 }
74}
75```
76
77This is useful when no form state is needed during loading. Creating a fresh
78editor for a different record also makes record changes explicit.
79
80## Create the form before data arrives
81
82Provide a static, shape-complete fallback, then call `form.update(...)` when
83the query result changes. Keep option creation in one function so callbacks and
84validation settings remain consistent.
85
86```ts
87import { TanStackFormController, formOptions } from '@tanstack/lit-form'
88
89const emptyUser: User = {
90 firstName: '',
91 lastName: '',
92}
93
94class UserEditor extends LitElement {
95 private form = new TanStackFormController(this, this.options(emptyUser))
96
97 private options(defaultValues: User) {
98 return formOptions({
99 defaultValues,
100 onSubmit: async ({ value }) => {
101 await saveUser(value)
102 },
103 })
104 }
105
106 connectedCallback() {
107 super.connectedCallback()
108 void loadUser().then((user) => {
109 this.form.update(this.options(user))
110 this.requestUpdate()
111 })
112 }
113}
114```
115
116When loaded data replaces the fallback, TanStack Form applies the new defaults
117to untouched fields while preserving fields the user already touched. You can
118hide the fields during loading or render the empty form immediately.
119
120The repository's `examples/lit/query-integration` example demonstrates this
121pattern with `QueryObserver` from TanStack Query Core.
122
123## Background refetches and record changes
124
125`defaultValues` establish the baseline; they are not a fully controlled
126`values` property. Later `form.update(...)` calls preserve touched fields.
127
128If a background refetch arrives while a user is editing, decide whether to keep
129local edits, prompt before replacing them, or deliberately call
130`form.api.reset(nextValues)`. Do not overwrite in-progress input merely because
131a query refreshed.
132
133When switching records, create a fresh editor element/controller or explicitly
134reset the existing form. Otherwise, touched values from the previous record can
135be preserved when new defaults arrive.