You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/1.getting-started/10.data-fetching.md
+59-3
Original file line number
Diff line number
Diff line change
@@ -56,7 +56,7 @@ In the example above, `useFetch` would make sure that the request would occur in
56
56
57
57
### Suspense
58
58
59
-
Nuxt uses Vue’s [`<Suspense>`](https://vuejs.org/guide/built-ins/suspense) component under the hood to prevent navigation before every async data is available to the view. The data fetching composables can help you leverage this feature and use what suits best on a per-call basis.
59
+
Nuxt uses Vue's [`<Suspense>`](https://vuejs.org/guide/built-ins/suspense) component under the hood to prevent navigation before every async data is available to the view. The data fetching composables can help you leverage this feature and use what suits best on a per-call basis.
60
60
61
61
::note
62
62
You can add the [`<NuxtLoadingIndicator>`](/docs/api/components/nuxt-loading-indicator) to add a progress bar between page navigations.
@@ -250,7 +250,7 @@ If you have not fetched data on the server (for example, with `server: false`),
250
250
251
251
### Lazy
252
252
253
-
By default, data fetching composables will wait for the resolution of their asynchronous function before navigating to a new page by using Vue’s Suspense. This feature can be ignored on client-side navigation with the `lazy` option. In that case, you will have to manually handle loading state using the `status` value.
253
+
By default, data fetching composables will wait for the resolution of their asynchronous function before navigating to a new page by using Vue's Suspense. This feature can be ignored on client-side navigation with the `lazy` option. In that case, you will have to manually handle loading state using the `status` value.
254
254
255
255
```vue twoslash [app.vue]
256
256
<script setup lang="ts">
@@ -350,14 +350,70 @@ Both `pick` and `transform` don't prevent the unwanted data from being fetched i
350
350
[`useFetch`](/docs/api/composables/use-fetch) and [`useAsyncData`](/docs/api/composables/use-async-data) use keys to prevent refetching the same data.
351
351
352
352
-[`useFetch`](/docs/api/composables/use-fetch) uses the provided URL as a key. Alternatively, a `key` value can be provided in the `options` object passed as a last argument.
353
-
-[`useAsyncData`](/docs/api/composables/use-async-data) uses its first argument as a key if it is a string. If the first argument is the handler function that performs the query, then a key that is unique to the file name and line number of the instance of`useAsyncData`will be generated for you.
353
+
-[`useAsyncData`](/docs/api/composables/use-async-data) uses its first argument as a key if it is a string. If the first argument is the handler function that performs the query, then a key that is unique to the file name and line number of the instance of`useAsyncData`will be generated for you.
354
354
355
355
::tip
356
356
To get the cached data by key, you can use [`useNuxtData`](/docs/api/composables/use-nuxt-data)
357
357
::
358
358
359
359
:video-accordion{title="Watch a video from Vue School on caching data with the key option"videoId="1026410044"platform="vimeo"}
360
360
361
+
#### Shared State and Option Consistency
362
+
363
+
When multiple components use the same key with `useAsyncData` or `useFetch`, they will share the same `data`, `error` and `status` refs. This ensures consistency across components but requires some options to be consistent.
364
+
365
+
The following options **must be consistent** across all calls with the same key:
You can use computed refs, plain refs or getter functions as keys, allowing for dynamic data fetching that automatically updates when dependencies change:
403
+
404
+
```ts
405
+
// Using a computed property as a key
406
+
const userId =ref('123')
407
+
const { data: user } =useAsyncData(
408
+
computed(() =>`user-${userId.value}`),
409
+
() =>fetchUser(userId.value)
410
+
)
411
+
412
+
// When userId changes, the data will be automatically refetched
413
+
// and the old data will be cleaned up if no other components use it
414
+
userId.value='456'
415
+
```
416
+
361
417
#### Refresh and execute
362
418
363
419
If you want to fetch or refresh data manually, use the `execute` or `refresh` function provided by the composables.
Nuxt's data fetching system (`useAsyncData` and `useFetch`) has been significantly reorganized for better performance and consistency:
235
+
236
+
1.**Shared refs for the same key**: All calls to `useAsyncData` or `useFetch` with the same key now share the same `data`, `error` and `status` refs. This means that it is important that all calls with an explicit key must not have conflicting `deep`, `transform`, `pick`, `getCachedData` or `default` options.
237
+
238
+
2.**More control over `getCachedData`**: The `getCachedData` function is now called every time data is fetched, even if this is caused by a watcher or calling `refreshNuxtData`. (Previously, new data was always fetched and this function was not called in these cases.) To allow more control over when to use cached data and when to refetch, the function now receives a context object with the cause of the request.
239
+
240
+
3.**Reactive key support**: You can now use computed refs, plain refs or getter functions as keys, which enables automatic data refetching (and stores data separately).
241
+
242
+
4.**Data cleanup**: When the last component using data fetched with `useAsyncData` is unmounted, Nuxt will remove that data to avoid ever-growing memory usage.
243
+
244
+
#### Reasons for Change
245
+
246
+
These changes have been made to improve memory usage and increase consistency with loading states across calls of `useAsyncData`.
247
+
248
+
#### Migration Steps
249
+
250
+
1.**Check for inconsistent options**: Review any components using the same key with different options or fetch functions.
Whether to call and use the result from `getCachedData` when refreshing data for `useAsyncData` and `useFetch` (whether by `watch`, `refreshNuxtData()`, or a manual `refresh()` call.
You can use a computed ref, plain ref or a getter function as the key, allowing for dynamic data fetching that automatically updates when the key changes:
// When the route changes and userId updates, the data will be automatically refetched
66
+
const { data: user } = useAsyncData(
67
+
userId,
68
+
() => fetchUserById(route.params.id)
69
+
)
70
+
</script>
71
+
```
72
+
56
73
::warning
57
-
[`useAsyncData`](/docs/api/composables/use-async-data) is a reserved function name transformed by the compiler, so you should not name your own function [`useAsyncData`](/docs/api/composables/use-async-data).
74
+
[`useAsyncData`](/docs/api/composables/use-async-data) is a reserved function name transformed by the compiler, so you should not name your own function [`useAsyncData`](/docs/api/composables/use-async-data).
You can use a computed ref or a plain ref as the URL, allowing for dynamic data fetching that automatically updates when the URL changes:
72
+
73
+
```vue [pages/[id\\].vue]
74
+
<script setup lang="ts">
75
+
const route = useRoute()
76
+
const id = computed(() => route.params.id)
77
+
78
+
// When the route changes and id updates, the data will be automatically refetched
79
+
const { data: post } = await useFetch(() => `/api/posts/${id.value}`)
80
+
</script>
81
+
```
82
+
83
+
When using `useFetch` with the same URL and options in multiple components, they will share the same `data`, `error` and `status` refs. This ensures consistency across components.
84
+
69
85
::warning
70
86
`useFetch` is a reserved function name transformed by the compiler, so you should not name your own function `useFetch`.
71
87
::
@@ -109,7 +125,7 @@ All fetch options can be given a `computed` or `ref` value. These will be watche
109
125
-`transform`: a function that can be used to alter `handler` function result after resolving
110
126
-`getCachedData`: Provide a function which returns cached data. A `null` or `undefined` return value will trigger a fetch. By default, this is:
0 commit comments