Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

Commit

Permalink
docs: add information on how to use options api asyncData
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Aug 29, 2022
1 parent 25ef26c commit 8c73987
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
21 changes: 21 additions & 0 deletions docs/content/2.guide/2.features/5.data-fetching.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,27 @@ const refresh = () => refreshNuxtData('count')
</script>
```

## Options API support

Nuxt 3 provides a way to perform `asyncData` fetching within the Options API. You must wrap your component definition within `defineNuxtComponent` for this to work.

```vue
<script>
export default defineNuxtComponent({
fetchKey: 'hello',
async asyncData () {
return {
hello: await $fetch('/api/hello')
}
}
})
</script>
```

::alert{type=warning}
Options API support for `asyncData` may well change before the stable release of Nuxt 3.
::

## Isomorphic `fetch` and `$fetch`

When we call `fetch` in the browser, user headers like `cookie` will be directly sent to the API. But during server-side-rendering, since the `fetch` request takes place 'internally' within the server, it doesn't include the user's browser cookies, nor does it pass on cookies from the fetch response.
Expand Down
8 changes: 8 additions & 0 deletions test/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,14 @@ describe('head tags', () => {
// })
})

describe('legacy async data', () => {
it('should work with defineNuxtComponent', async () => {
const html = await $fetch('/legacy/async-data')
expect(html).toContain('<div>Hello API</div>')
expect(html).toContain('{hello:"Hello API"}')
})
})

describe('navigate', () => {
it('should redirect to index with navigateTo', async () => {
const { headers } = await fetch('/navigate-to/', { redirect: 'manual' })
Expand Down
15 changes: 15 additions & 0 deletions test/fixtures/basic/pages/legacy/async-data.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<template>
<div>
{{ hello }}
</div>
</template>

<script>
export default defineNuxtComponent({
async asyncData () {
return {
hello: await $fetch('/api/hello')
}
}
})
</script>

0 comments on commit 8c73987

Please sign in to comment.