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

suspense.md

94 lines3.9 KB

1---
2id: suspense
3title: Suspense (experimental)
4---
5​
6> NOTE: Suspense mode for Vue Query is experimental, same as Vue's Suspense itself. These APIs WILL change and should not be used in production unless you lock both your Vue and Vue Query versions to patch-level versions that are compatible with each other.
7​
8Vue Query can also be used with Vue's new [Suspense](https://vuejs.org/guide/built-ins/suspense.html) API's.
9​
10To do that you need to wrap your suspendable component with `Suspense` component provided by Vue
11​
12```vue
13<script setup>
14import SuspendableComponent from './SuspendableComponent.vue'
15</script>
16​
17<template>
18 <Suspense>
19 <template #default>
20 <SuspendableComponent />
21 </template>
22 <template #fallback>
23 <div>Loading...</div>
24 </template>
25 </Suspense>
26</template>
27```
28​
29And change your `setup` function in suspendable component to be `async`. Then you can use async `suspense` function that is provided by `vue-query` (both `useQuery` and `useInfiniteQuery` return it).
30​
31```vue
32<script>
33import { defineComponent } from 'vue'
34import { useQuery } from '@tanstack/vue-query'
35​
36const todoFetcher = async () =>
37 await fetch('https://jsonplaceholder.cypress.io/todos').then((response) =>
38 response.json(),
39 )
40export default defineComponent({
41 name: 'SuspendableComponent',
42 async setup() {
43 const { data, suspense } = useQuery({
44 queryKey: ['todos'],
45 queryFn: todoFetcher,
46 })
47 await suspense()
48​
49 return { data }
50 },
51})
52</script>
53```
54​
55## How `suspense()` resolves
56​
57- If the query has no data or its data is stale, it fetches the query and resolves with the result once that fetch resolves. This is usually when the query function finishes, but can be earlier, such as after the first chunk of an `experimental_streamedQuery` or when `setQueryData` sets data while the fetch is in flight.
58- If the data is fresh, it resolves immediately without refetching.
59- While the query is disabled (`enabled: false`), it waits until the query is enabled, so it never resolves for a query that stays disabled. On the server, this blocks the render, see [SSR](./ssr.md#suspense-of-a-query-that-stays-disabled-blocks-the-render-on-the-server).
60- If the fetch fails, it resolves with the query result in the error state. It rejects with the error only when `throwOnError` is (or returns) `true`.
61​
62## Error handling
63​
64Since `suspense()` resolves with the error result by default, the component still renders after a failed fetch and can read `error` from the query. To let a parent component handle the error instead, set `throwOnError: true`. `await suspense()` then rejects, the error propagates out of the `async` `setup`, and you can catch it with [`onErrorCaptured`](https://vuejs.org/api/composition-api-lifecycle.html#onerrorcaptured) in a parent of `Suspense`:
65​
66```vue
67<script setup>
68import { onErrorCaptured, ref } from 'vue'
69import SuspendableComponent from './SuspendableComponent.vue'
70​
71const error = ref(null)
72​
73onErrorCaptured((err) => {
74 error.value = err
75 return false
76})
77</script>
78​
79<template>
80 <div v-if="error">Something went wrong: {{ error.message }}</div>
81 <Suspense v-else>
82 <template #default>
83 <SuspendableComponent />
84 </template>
85 <template #fallback>
86 <div>Loading...</div>
87 </template>
88 </Suspense>
89</template>
90```
91​
92## Fetch-on-render vs Render-as-you-fetch
93​
94Out of the box, Vue 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.