Open History to see the last commit
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 { createForm } from '@tanstack/solid-form'
21import { createQuery } from '@tanstack/solid-query'
22import { Show } from 'solid-js'
23β
24export default function App() {
25 const query = createQuery(() => ({
26 queryKey: ['data'],
27 queryFn: async () => {
28 await new Promise((resolve) => setTimeout(resolve, 1000))
29 return { firstName: 'FirstName', lastName: 'LastName' }
30 },
31 }))
32β
33 const form = createForm(() => ({
34 defaultValues: {
35 firstName: query.data?.firstName ?? '',
36 lastName: query.data?.lastName ?? '',
37 },
38 onSubmit: async ({ value }) => {
39 // Do something with form data
40 console.log(value)
41 },
42 }))
43β
44 return (
45 <Show when={!query.isLoading} fallback={<p>Loading..</p>}>
46 <></>
47 </Show>
48 )
49}
50```
51β
52This 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.