useFetch

This composable provides a convenient wrapper around useAsyncData and $fetch. It automatically generates a key based on URL and fetch options, as well as infers API response type.

Type

Signature

  1. function useFetch(
  2. url: string,
  3. options?: UseFetchOptions
  4. ): Promise<DataT>
  5. type UseFetchOptions = {
  6. method?: string,
  7. params?: SearchParams,
  8. headers?: {key: string, value: string}[],
  9. baseURL?: string,
  10. server?: boolean
  11. lazy?: boolean
  12. default?: () => DataT
  13. transform?: (input: DataT) => DataT
  14. pick?: string[]
  15. }
  16. type DataT = {
  17. data: Ref<DataT>
  18. pending: Ref<boolean>
  19. refresh: () => Promise<void>
  20. error: Ref<any>
  21. }

Params

  • Url: The URL to fetch
  • Options (from ohmyfetch):
    • method: Request method
    • params: Query params
    • headers: Request headers
    • baseURL: Base URL for the request
  • Options (from useAsyncData):
    • lazy: Whether to resolve the async function after loading the route, instead of blocking navigation (defaults to false).
    • 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.
    • transform: A function that can be used to alter handler function result after resolving.

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: 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. Passing true as parameter skips that wait.

Example

  1. const { data, pending, error, refresh } = useFetch(
  2. 'https://api.nuxtjs.dev/mountains',
  3. {
  4. pick: ['title']
  5. }
  6. )

👉

Read more in Guide > Features > Data Fetching.

🔎

Read and edit a live example in Examples > Composables > Use Fetch