2021-04-20 12:16:09 +00:00
# Data Fetching
2021-06-08 21:44:30 +00:00
Nuxt provides `asyncData` to handle data fetching within you application.
## `asyncData`
2021-08-10 00:27:23 +00:00
Within your pages and components you can use `asyncData` to get access to data that resolves asynchronously.
2021-06-08 21:44:30 +00:00
### Usage
```js
asyncData(key: string, fn: () => Object, options?: { defer: boolean, server: boolean })
```
* **key**: a unique key to ensure that data fetching can be properly de-duplicated across requests
2021-09-23 14:45:59 +00:00
* **fn** an asynchronous function that **must return an object** .
2021-06-08 21:44:30 +00:00
* **options**:
- _defer_: whether to load the route before resolving the async function (defaults to `false` )
- _server_: whether the fetch the data on server-side (defaults to `true` )
Under the hood, `defer: false` uses `<Suspense>` to block the loading of the route before the data has been fetched. Consider using `defer: true` and implementing a loading state instead for a snappier user experience.
2021-06-16 12:42:58 +00:00
This helper only works with:
- a component defined with `defineNuxtComponent`
- `<script setup nuxt>` syntax block
2021-06-08 21:44:30 +00:00
### Example
2021-09-23 14:45:59 +00:00
```vue
< script setup nuxt >
const { data } = asyncData('time', () => $fetch('/api/count'))
< / script >
< template >
Page visits: {{ data.count }}
< / template >
```
If you don't want to use the `<script setup>` syntax, you need to use the `defineNuxtComponent` method to define your component:
2021-06-08 21:44:30 +00:00
```vue
< template >
Page visits: {{ data.count }}
< / template >
< script >
export default defineNuxtComponent({
setup () {
const { data } = asyncData('time', () => $fetch('/api/count'))
return { data }
}
})
< / script >
```
2021-06-16 12:42:58 +00:00