2022-04-06 05:56:08 +00:00
# `useFetch`
2022-10-06 09:15:30 +00:00
This composable provides a convenient wrapper around [`useAsyncData` ](/api/composables/use-async-data ) and [`$fetch` ](/api/utils/$fetch ).
It automatically generates a key based on URL and fetch options, provides type hints for request url based on server routes, and infers API response type.
2022-04-13 17:14:03 +00:00
## Type
```ts [Signature]
function useFetch(
2022-07-07 16:26:04 +00:00
url: string | Request | Ref< string | Request > | () => string | Request,
options?: UseFetchOptions< DataT >
): Promise< AsyncData < DataT > >
2022-04-13 17:14:03 +00:00
type UseFetchOptions = {
2022-08-07 09:57:10 +00:00
key?: string
method?: string
params?: SearchParams
2022-05-20 09:04:37 +00:00
body?: RequestInit['body'] | Record< string , any >
2022-08-07 09:57:10 +00:00
headers?: { key: string, value: string }[]
baseURL?: string
2022-04-13 17:14:03 +00:00
server?: boolean
lazy?: boolean
2022-09-07 09:47:40 +00:00
immediate?: boolean
2022-04-13 17:14:03 +00:00
default?: () => DataT
transform?: (input: DataT) => DataT
pick?: string[]
2022-06-22 10:41:34 +00:00
watch?: WatchSource[]
2022-07-14 21:30:05 +00:00
initialCache?: boolean
2022-04-13 17:14:03 +00:00
}
2022-07-07 16:26:04 +00:00
type AsyncData< DataT > = {
2022-04-13 17:14:03 +00:00
data: Ref< DataT >
pending: Ref< boolean >
refresh: () => Promise< void >
2022-09-07 09:47:40 +00:00
execute: () => Promise< void >
2022-04-29 18:42:22 +00:00
error: Ref< Error | boolean >
2022-04-13 17:14:03 +00:00
}
2022-04-06 05:56:08 +00:00
```
2022-04-13 17:14:03 +00:00
## Params
2022-04-06 05:56:08 +00:00
2022-08-07 09:57:10 +00:00
* **Url**: The URL to fetch.
2022-05-20 09:04:37 +00:00
* **Options (extends [unjs/ohmyfetch ](https://github.com/unjs/ohmyfetch ) options & [AsyncDataOptions ](/api/composables/use-async-data#params ))**:
2022-08-07 09:57:10 +00:00
* `method` : Request method.
* `params` : Query params.
2022-05-20 09:04:37 +00:00
* `body` : Request body - automatically stringified (if an object is passed).
2022-08-07 09:57:10 +00:00
* `headers` : Request headers.
* `baseURL` : Base URL for the request.
2022-04-13 17:14:03 +00:00
* **Options (from `useAsyncData` )**:
2022-09-03 10:56:12 +00:00
* `key` : a unique key to ensure that data fetching can be properly de-duplicated across requests, if not provided, it will be generated based on the static code location where `useAyncData` is used.
2022-04-16 13:53:36 +00:00
* `server` : Whether to fetch the data on the server (defaults to `true` ).
2022-04-13 17:14:03 +00:00
* `default` : A factory function to set the default value of the data, before the async function resolves - particularly useful with the `lazy: true` option.
2022-04-16 13:53:36 +00:00
* `pick` : Only pick specified keys in this array from the `handler` function result.
2022-08-07 09:57:10 +00:00
* `watch` : watch reactive sources to auto-refresh.
* `initialCache` : When set to `false` , will skip payload cache for initial fetch (defaults to `true` ).
2022-04-13 17:14:03 +00:00
* `transform` : A function that can be used to alter `handler` function result after resolving.
2022-09-07 09:47:40 +00:00
* `immediate` : When set to `false` , will prevent the request from firing immediately. (defaults to `true` )
2022-04-13 17:14:03 +00:00
2022-07-07 16:26:04 +00:00
::alert{type=warning}
If you provide a function or ref as the `url` parameter, or if you provide functions as arguments to the `options` parameter, then the `useFetch` call will not match other `useFetch` calls elsewhere in your codebase, even if the options seem to be identical. If you wish to force a match, you may provide your own key in `options` .
::
2022-08-13 07:27:04 +00:00
## Return Values
2022-04-06 05:56:08 +00:00
2022-08-07 09:57:10 +00:00
* **data**: the result of the asynchronous function that is passed in.
* **pending**: a boolean indicating whether the data is still being fetched.
2022-09-07 09:47:40 +00:00
* **refresh**/**execute** : a function that can be used to refresh the data returned by the `handler` function.
2022-08-07 09:57:10 +00:00
* **error**: an error object if the data fetching failed.
2022-04-13 17:14:03 +00:00
2022-09-03 11:02:21 +00:00
By default, Nuxt waits until a `refresh` is finished before it can be executed again.
::alert{type=warning}
If you have not fetched data on the server (for example, with `server: false` ), then the data _will not_ be fetched until hydration completes. This means even if you await `useFetch` on client-side, `data` will remain null within `<script setup>` .
::
2022-04-13 17:14:03 +00:00
## Example
```ts
2022-09-05 07:42:15 +00:00
const { data, pending, error, refresh } = await useFetch('https://api.nuxtjs.dev/mountains',{
2022-04-13 17:14:03 +00:00
pick: ['title']
2022-09-05 07:42:15 +00:00
})
```
Using [interceptors ](https://github.com/unjs/ohmyfetch#%EF%B8%8F-interceptors ):
```ts
const { data, pending, error, refresh } = await useFetch('/api/auth/login', {
onRequest({ request, options }) {
// Set the request headers
options.headers = options.headers || {}
options.headers.authorization = '...'
},
onRequestError({ request, options, error }) {
// Handle the request errors
},
onResponse({ request, response, options }) {
// Process the response data
return response._data
},
onResponseError({ request, response, options }) {
2022-09-07 08:23:49 +00:00
// Handle the response errors
2022-04-13 17:14:03 +00:00
}
2022-09-05 07:42:15 +00:00
})
2022-04-13 17:14:03 +00:00
```
2022-04-06 05:56:08 +00:00
2022-09-13 12:54:31 +00:00
:ReadMore{link="/getting-started/data-fetching"}
2022-04-06 05:56:08 +00:00
2022-04-13 17:14:03 +00:00
:LinkExample{link="/examples/composables/use-fetch"}