Nuxt/docs/content/1.docs/3.api/1.composables/use-fetch.md
Sébastien Chopin 90784f79d7
docs: new website design (#9007)
* docs: implement new website theme

* chore: rename dirs

* chore: update build

* lint fix

* chore: update deps

* fix: include node_modules in esbuild step

* chore: update deps

* Update .gitignore

* chore: update theme version

* up

* up

* fix: use svg for illustration

* chore: update to 0.0.12

* chore: force parse5 resolution

* stay with build

* feat: always display first home section

* Update yarn.lock

* chore: update theme

* fix lint

* docs: update home title

* chore: update website theme version

* Update docs/content/0.index.md

Co-authored-by: pooya parsa <pyapar@gmail.com>

* Update docs/content/0.index.md

Co-authored-by: pooya parsa <pyapar@gmail.com>

* up

* chore: bump theme version

* up

* chore: up

* up up and up

* chore: generate

* fix: boolean value

* feat: new images

* update again

* chore: up

* ouep

* chore: up

Co-authored-by: Daniel Roe <daniel@roe.dev>
Co-authored-by: Clément Ollivier <clement.o2p@gmail.com>
Co-authored-by: pooya parsa <pyapar@gmail.com>
2022-11-16 11:04:28 +01:00

4.9 KiB

useFetch

This composable provides a convenient wrapper around useAsyncData and $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.

Type

function useFetch(
  url: string | Request | Ref<string | Request> | () => string | Request,
  options?: UseFetchOptions<DataT>
): Promise<AsyncData<DataT>>

type UseFetchOptions = {
  key?: string
  method?: string
  query?: SearchParams
  params?: SearchParams
  body?: RequestInit['body'] | Record<string, any>
  headers?: { key: string, value: string }[]
  baseURL?: string
  server?: boolean
  lazy?: boolean
  immediate?: boolean
  default?: () => DataT
  transform?: (input: DataT) => DataT
  pick?: string[]
  watch?: WatchSource[]
}

type AsyncData<DataT> = {
  data: Ref<DataT>
  pending: Ref<boolean>
  refresh: (opts?: { dedupe?: boolean }) => Promise<void>
  execute: () => Promise<void>
  error: Ref<Error | boolean>
}

Params

  • URL: The URL to fetch.
  • Options (extends unjs/ofetch options & AsyncDataOptions):
    • method: Request method.
    • query: Adds query search params to URL using ufo
    • params: Alias for query
    • body: Request body - automatically stringified (if an object is passed).
    • headers: Request headers.
    • baseURL: Base URL for the request.

::alert{type=info} All fetch options can be given a computed or ref value. These will be watched and new requests made automatically with any new values if they are updated. ::

  • Options (from useAsyncData):
    • 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 useAsyncData is used.
    • server: Whether to fetch the data on the server (defaults to true).
    • default: A factory function to set the default value of the data, before the async function resolves - particularly useful with the lazy: true option.
    • pick: Only pick specified keys in this array from the handler function result.
    • watch: watch reactive sources to auto-refresh.
    • transform: A function that can be used to alter handler function result after resolving.
    • immediate: When set to false, will prevent the request from firing immediately. (defaults to true)

::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. ::

Return Values

  • data: the result of the asynchronous function that is passed in.
  • pending: a boolean indicating whether the data is still being fetched.
  • refresh/execute : a function that can be used to refresh the data returned by the handler function.
  • error: an error object if the data fetching failed.

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>. ::

Example

const { data, pending, error, refresh } = await useFetch('https://api.nuxtjs.dev/mountains',{
    pick: ['title']
})

Adding Query Search Params:

Using the query option, you can add search parameters to your query. This option is extended from unjs/ofetch and is using unjs/ufo to create the URL. Objects are automatically stringified.

const param1 = ref('value1')
const { data, pending, error, refresh } = await useFetch('https://api.nuxtjs.dev/mountains',{
    query: { param1, param2: 'value2' }
})

Results in https://api.nuxtjs.dev/mountains?param1=value1&param2=value2

Using interceptors:

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 }) {
    // Handle the response errors
  }
})

:ReadMore{link="/docs/getting-started/data-fetching"}

::LinkExample{link="/docs/examples/composables/use-fetch"} ::