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

suspense.md

41 lines1.7 KB

1---
2id: suspense
3title: Suspense
4---
5​
6Solid Query can also be used with Solid's [Suspense](https://v1.solidjs.com/reference/components/suspense) API.
7​
8To do that you need to wrap your suspendable component with `Suspense` component provided by Solid
9​
10```tsx
11import { Suspense } from 'solid-js'
12;<Suspense fallback={<LoadingSpinner />}>
13 <SuspendableComponent />
14</Suspense>
15```
16​
17Then read the query's `data` inside that boundary. The `data` property is a Solid resource, so reading it suspends the component until the query has data.
18​
19```tsx
20import { useQuery } from '@tanstack/solid-query'
21​
22const todoFetcher = async () =>
23 await fetch('https://jsonplaceholder.cypress.io/todos').then((response) =>
24 response.json(),
25 )
26​
27function SuspendableComponent() {
28 const todosQuery = useQuery(() => ({
29 queryKey: ['todos'],
30 queryFn: todoFetcher,
31 }))
32​
33 // Accessing todosQuery.data directly inside a <Suspense> boundary
34 // automatically triggers suspension until data is ready
35 return <div>Data: {JSON.stringify(todosQuery.data)}</div>
37```
38​
39## Fetch-on-render vs Render-as-you-fetch
40​
41Out of the box, Solid Query in `suspense` mode works really well as a **Fetch-on-render** solution with no additional configuration. This means that when your components attempt to mount, they will trigger query fetching and suspend, but only once you have imported them and mounted them. If you want to take it to the next level and implement a **Render-as-you-fetch** model, we recommend implementing [Prefetching](./prefetching) on routing callbacks and/or user interactions events to start loading queries before they are mounted and hopefully even before you start importing or mounting their parent components.