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
8Form should own the editable copy.
9β
10There are two useful patterns for async initial values in Angular: resolve the
11data before constructing the form, or construct the form immediately with
12complete fallback values and reset it when data arrives.
13β
14## Resolve data before constructing the editor
15β
16Angular Router resolvers can make the record available synchronously when the
17editor component is constructed. This lets `defaultValues` start with the
18complete loaded value.
19β
20```ts
21import { Component, inject } from '@angular/core'
22import { ActivatedRoute } from '@angular/router'
23import type { ResolveFn, Routes } from '@angular/router'
24import { injectForm } from '@tanstack/angular-form'
25β
26type User = {
27 firstName: string
28 lastName: string
29}
30β
31export const userResolver: ResolveFn<User> = async (route) => {
32 const response = await fetch(`/api/users/${route.paramMap.get('userId')}`)
33 return response.json()
34}
35β
36@Component({
37 selector: 'app-user-editor',
38 standalone: true,
39 template: `<form><!-- fields --></form>`,
40})
41export class UserEditorComponent {
42 private route = inject(ActivatedRoute)
43 private user = this.route.snapshot.data['user'] as User
44β
45 form = injectForm({
46 defaultValues: this.user,
47 onSubmit: async ({ value }) => {
48 await fetch('/api/users', {
49 method: 'PUT',
50 headers: { 'content-type': 'application/json' },
51 body: JSON.stringify(value),
52 })
53 },
54 })
55}
56β
57export const routes: Routes = [
58 {
59 path: 'users/:userId',
60 component: UserEditorComponent,
61 resolve: { user: userResolver },
62 },
63]
64```
65β
66This pattern is useful when no form state is needed during loading. It gives
67the form complete data on its initial construction. If the router reuses the
68same component instance for another record, reset that form from the new
69resolved data or arrange for a fresh editor instance.
70β
71## Create the form before data arrives
72β
73You can instead use `injectForm` in the same component as `injectQuery`.
74Provide a static, shape-complete fallback so `defaultValues` are never
75`undefined`, then deliberately reset the untouched form when query data
76arrives.
77β
78```ts
79import { Component, effect, inject } from '@angular/core'
80import { ActivatedRoute } from '@angular/router'
81import { injectQuery } from '@tanstack/angular-query-experimental'
82import { injectForm } from '@tanstack/angular-form'
83β
84type User = {
85 firstName: string
86 lastName: string
87}
88β
89const emptyUser: User = {
90 firstName: '',
91 lastName: '',
92}
93β
94@Component({
95 selector: 'app-user-page',
96 standalone: true,
97 template: `
98 @if (userQuery.isPending()) {
99 <p>Loadingβ¦</p>
100 } @else if (userQuery.isError()) {
101 <p role="alert">Could not load the user.</p>
102 } @else {
103 <form><!-- fields --></form>
104 }
105 `,
106})
107export class UserPageComponent {
108 private route = inject(ActivatedRoute)
109 private userId = this.route.snapshot.paramMap.get('userId')!
110β
111 userQuery = injectQuery(() => ({
112 queryKey: ['user', this.userId],
113 queryFn: async (): Promise<User> => {
114 const response = await fetch(`/api/users/${this.userId}`)
115 return response.json()
116 },
117 }))
118β
119 form = injectForm({
120 defaultValues: emptyUser,
121 onSubmit: async ({ value }) => {
122 await fetch('/api/users', {
123 method: 'PUT',
124 headers: { 'content-type': 'application/json' },
125 body: JSON.stringify(value),
126 })
127 },
128 })
129β
130 constructor() {
131 effect(() => {
132 const user = this.userQuery.data()
133 if (user && !this.form.state.isTouched) {
134 this.form.reset(user)
135 }
136 })
137 }
138}
139```
140β
141In this example, fields remain unmounted during loading, so the user cannot
142edit them before the loaded values arrive. You can render the empty form
143immediately when that better suits the UI, but then decide how incoming data
144should interact with edits.
145β
146This is the approach demonstrated by the repository's
147`examples/angular/query-integration` example.
148β
149## Background refetches and record changes
150β
151`defaultValues` establish the form's baseline; they are not a fully controlled
152`values` prop. When background data arrives, decide at the product level
153whether to keep local edits, prompt before replacing them, or call
154`form.reset(nextValues)` deliberately. Do not overwrite in-progress input
155merely because a query refreshed.
156β
157When switching to a different record, construct a fresh editor or deliberately
158reset the existing form. Otherwise, values from the previous record can remain
159in the form.