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

async-initial-values.md

51 lines1.6 KB

1---
2id: async-initial-values
3title: Async Initial Values
4---
5​
6Let's say that you want to fetch some data from an API and use it as the initial value of a form.
7​
8While this problem sounds simple on the surface, there are hidden complexities you might not have thought of thus far.
9​
10For example, you might want to show a loading spinner while the data is being fetched, or you might want to handle errors gracefully.
11Likewise, you could also find yourself looking for a way to cache the data so that you don't have to fetch it every time the form is rendered.
12​
13While we could implement many of these features from scratch, it would end up looking a lot like another project we maintain: [TanStack Query](https://tanstack.com/query).
14​
15As such, this guide shows you how you can mix-n-match TanStack Form with TanStack Query to achieve the desired behavior.
16​
17## Basic Usage
18​
19```tsx
20import { useForm } from '@tanstack/react-form'
21import { useQuery } from '@tanstack/react-query'
22​
23export default function App() {
24 const {data, isLoading} = useQuery({
25 queryKey: ['data'],
26 queryFn: async () => {
27 await new Promise((resolve) => setTimeout(resolve, 1000))
28 return {firstName: 'FirstName', lastName: "LastName"}
29 }
30 })
31​
32 const form = useForm({
33 defaultValues: {
34 firstName: data?.firstName ?? '',
35 lastName: data?.lastName ?? '',
36 },
37 onSubmit: async ({ value }) => {
38 // Do something with form data
39 console.log(value)
40 },
41 })
42​
43 if (isLoading) return <p>Loading...</p>
44​
45 return (
46 // ...
47 )
49```
50​
51This will show a loading spinner until the data is fetched, and then it will render the form with the fetched data as the initial values.