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

async-initial-values.md

52 lines1.7 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 { 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 )
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.