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
11the form until the data is ready, or create it immediately with complete
12fallback values. Choose the approach that best matches the loading experience
13your UI needs.
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```vue
21<!-- UserPage.vue -->
22<script setup lang="ts">
23import { toRef } from 'vue'
24import { useQuery } from '@tanstack/vue-query'
25import UserEditor from './UserEditor.vue'
26import type { User } from './types.ts'
27
28const props = defineProps<{ userId: string }>()
29const userId = toRef(props, 'userId')
30const {
31 data: user,
32 isPending,
33 isError,
34} = useQuery({
35 queryKey: ['user', userId],
36 queryFn: async (): Promise<User> => {
37 const response = await fetch(`/api/users/${userId.value}`)
38 return response.json()
39 },
40})
41</script>
42
43<template>
44 <p v-if="isPending">Loading…</p>
45 <p v-else-if="isError" role="alert">Could not load the user.</p>
46 <UserEditor v-else-if="user" :key="userId" :user="user" />
47</template>
48```
49
50```vue
51<!-- UserEditor.vue -->
52<script setup lang="ts">
53import { useForm } from '@tanstack/vue-form'
54import type { User } from './types.ts'
55
56const props = defineProps<{ user: User }>()
57const form = useForm({
58 defaultValues: props.user,
59 onSubmit: async ({ value }) => {
60 await fetch('/api/users', {
61 method: 'PUT',
62 headers: { 'content-type': 'application/json' },
63 body: JSON.stringify(value),
64 })
65 },
66})
67</script>
68
69<template>
70 <form @submit.prevent="form.handleSubmit()">
71 <!-- fields -->
72 </form>
73</template>
74```
75
76This pattern is useful when no form state is needed during loading. Mounting
77the editor only after data exists also makes it explicit when switching records
78should create a fresh form. The `:key` recreates the editor when `userId`
79changes.
80
81## Create the form before data arrives
82
83You can instead call `useForm` in the same component as `useQuery`. Provide a
84static, shape-complete fallback so `defaultValues` are never `undefined`, then
85update a reactive options object when data arrives.
86
87```vue
88<script setup lang="ts">
89import { reactive, toRef, watchEffect } from 'vue'
90import { useQuery } from '@tanstack/vue-query'
91import { useForm } from '@tanstack/vue-form'
92import type { User } from './types.ts'
93
94const props = defineProps<{ userId: string }>()
95const userId = toRef(props, 'userId')
96const emptyUser: User = {
97 firstName: '',
98 lastName: '',
99}
100
101const {
102 data: user,
103 isPending,
104 isError,
105} = useQuery({
106 queryKey: ['user', userId],
107 queryFn: async (): Promise<User> => {
108 const response = await fetch(`/api/users/${userId.value}`)
109 return response.json()
110 },
111})
112
113const formOptions = reactive({
114 defaultValues: emptyUser,
115 onSubmit: async ({ value }: { value: User }) => {
116 await fetch('/api/users', {
117 method: 'PUT',
118 headers: { 'content-type': 'application/json' },
119 body: JSON.stringify(value),
120 })
121 },
122})
123
124watchEffect(() => {
125 if (user.value) {
126 formOptions.defaultValues = user.value
127 }
128})
129
130const form = useForm(formOptions)
131</script>
132
133<template>
134 <p v-if="isPending">Loading…</p>
135 <p v-else-if="isError" role="alert">Could not load the user.</p>
136 <form v-else @submit.prevent="form.handleSubmit()">
137 <!-- fields -->
138 </form>
139</template>
140```
141
142The Vue adapter observes the reactive options object. When query data replaces
143the fallback, TanStack Form applies the new `defaultValues` to untouched fields
144while preserving fields the user has already touched. In this example, the
145fields remain unmounted during loading, so the user cannot edit them before the
146loaded values arrive. You can also render the empty form immediately when that
147better suits the UI.
148
149## Background refetches and record changes
150
151`defaultValues` establish the form's baseline; they are not a fully controlled
152`values` prop. In the fallback pattern, later `defaultValues` updates use the
153same touched-field-preserving behavior.
154
155If background refetches arrive while a user is editing, decide at the product
156level whether to keep local edits, prompt before replacing them, or call
157`form.reset(nextValues)` deliberately. Do not overwrite in-progress input
158merely because a query refreshed.
159
160When switching to a different record, either remount a keyed editor as in the
161first pattern or deliberately reset the existing form. Otherwise, touched
162values from the previous record can be preserved when the new defaults arrive.