docs: adjust example and additional instructions of useNuxtData (#30570)

This commit is contained in:
Alex Liu 2025-01-14 04:48:20 +08:00 committed by GitHub
parent 47224895ff
commit 50edb86e3a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -9,11 +9,27 @@ links:
---
::note
`useNuxtData` gives you access to the current cached value of [`useAsyncData`](/docs/api/composables/use-async-data) , `useLazyAsyncData`, [`useFetch`](/docs/api/composables/use-fetch) and [`useLazyFetch`](/docs/api/composables/use-lazy-fetch) with explicitly provided key.
`useNuxtData` gives you access to the current cached value of [`useAsyncData`](/docs/api/composables/use-async-data) , [`useLazyAsyncData`](/docs/api/composables/use-lazy-async-data), [`useFetch`](/docs/api/composables/use-fetch) and [`useLazyFetch`](/docs/api/composables/use-lazy-fetch) with explicitly provided key.
::
## Usage
The `useNuxtData` composable is used to access the current cached value of data-fetching composables such as `useAsyncData`, `useLazyAsyncData`, `useFetch`, and `useLazyFetch`. By providing the key used during the data fetch, you can retrieve the cached data and use it as needed.
This is particularly useful for optimizing performance by reusing already-fetched data or implementing features like Optimistic Updates or cascading data updates.
To use `useNuxtData`, ensure that the data-fetching composable (`useFetch`, `useAsyncData`, etc.) has been called with an explicitly provided key.
## Params
- `key`: The unique key that identifies the cached data. This key should match the one used during the original data fetch.
## Return Values
- `data`: A reactive reference to the cached data associated with the provided key. If no cached data exists, the value will be `null`. This `Ref` automatically updates if the cached data changes, allowing seamless reactivity in your components.
## Example
The example below shows how you can use cached data as a placeholder while the most recent data is being fetched from the server.
```vue [pages/posts.vue]
@ -26,13 +42,15 @@ const { data } = await useFetch('/api/posts', { key: 'posts' })
```vue [pages/posts/[id\\].vue]
<script setup lang="ts">
// Access to the cached value of useFetch in posts.vue (parent route)
const { id } = useRoute().params
const { data: posts } = useNuxtData('posts')
const { data } = useLazyFetch(`/api/posts/${id}`, {
key: `post-${id}`,
const route = useRoute()
const { data } = useLazyFetch(`/api/posts/${route.params.id}`, {
key: `post-${route.params.id}`,
default() {
// Find the individual post from the cache and set it as the default value.
return posts.value.find(post => post.id === id)
return posts.value.find(post => post.id === route.params.id)
}
})
</script>
@ -40,7 +58,9 @@ const { data } = useLazyFetch(`/api/posts/${id}`, {
## Optimistic Updates
We can leverage the cache to update the UI after a mutation, while the data is being invalidated in the background.
The example below shows how implementing Optimistic Updates can be achieved using useNuxtData.
Optimistic Updates is a technique where the user interface is updated immediately, assuming a server operation will succeed. If the operation eventually fails, the UI is rolled back to its previous state.
```vue [pages/todos.vue]
<script setup lang="ts">
@ -52,28 +72,34 @@ const { data } = await useAsyncData('todos', () => $fetch('/api/todos'))
```vue [components/NewTodo.vue]
<script setup lang="ts">
const newTodo = ref('')
const previousTodos = ref([])
let previousTodos = []
// Access to the cached value of useAsyncData in todos.vue
const { data: todos } = useNuxtData('todos')
const { data } = await useFetch('/api/addTodo', {
const addTodo = async () => {
return $fetch('/api/addTodo', {
method: 'post',
body: {
todo: newTodo.value
},
onRequest () {
previousTodos.value = todos.value // Store the previously cached value to restore if fetch fails.
// Store the previously cached value to restore if fetch fails.
previousTodos = todos.value
todos.value.push(newTodo.value) // Optimistically update the todos.
// Optimistically update the todos.
todos.value = [...todos.value, newTodo.value]
},
onRequestError () {
todos.value = previousTodos.value // Rollback the data if the request failed.
onResponseError () {
// Rollback the data if the request failed.
todos.value = previousTodos
},
async onResponse () {
await refreshNuxtData('todos') // Invalidate todos in the background if the request succeeded.
// Invalidate todos in the background if the request succeeded.
await refreshNuxtData('todos')
}
})
}
</script>
```