Skip to content

useFetch-Like Composable ​

Returns the API response as Nuxt async data. Intended for data that requires reactive updates, e.g. when using data in templates.

useMyApiData is built on Nuxt's own useFetch, so it takes every useFetch option – key, lazy, server, immediate, default, transform, pick, watch, getCachedData, dedupe and the rest – and returns the same AsyncData. Only the options that pick where a request goes – baseURL and $fetch – are the endpoint's to decide, and params is left out in favor of query.

Placeholder

useMyApiData is a placeholder. The composable is generated based on the endpoint ID. For example, endpoint jsonPlaceholder generates useJsonPlaceholderData.

Return Values ​

useMyApiData returns data, refresh (alias execute), error, status and clear, as useFetch does.

By default, a refresh called while a request is pending cancels that request and sends a new one. Pass dedupe: 'defer' to wait for the pending one instead.

Type Declarations ​

ts
export type UseApiDataOptions<
  ResT,
  DataT = ResT,
  PickKeys extends KeysOf<DataT> = KeysOf<DataT>,
  DefaultT = undefined,
> = AsyncDataFetchOptions<ResT, DataT, PickKeys, DefaultT>
  & ComputedOptions<{
    method?: RequestMethod
    path?: Record<string, string>
    query?: FetchOptions['query']
    body?: FetchOptions['body']
  }>
  & {
    headers?: MaybeRefHeaders<FetchOptions['headers']>
  }

export type UseApiData = <
  ResT = unknown,
  ErrorT = unknown,
  DataT = ResT,
  PickKeys extends KeysOf<DataT> = KeysOf<DataT>,
  DefaultT = undefined,
>(
  path: MaybeRefOrGetter<string>,
  opts?: UseApiDataOptions<ResT, DataT, PickKeys, DefaultT>,
  autoKey?: string,
) => AsyncData<PickFrom<DataT, PickKeys> | DefaultT, NuxtError<ErrorT> | undefined>

The generic parameters follow useFetch: ResT types the response, ErrorT the error body, and DataT what transform turns the response into. data is typed after transform, pick and default.

Request Options ​

path, query, body and method accept a plain value, a ref or a getter, and headers a plain value or a ref, for the whole object or, in a record, per header. The request is sent again whenever one of them changes:

ts
const postId = ref(1)

const { data } = await useJsonPlaceholderData('comments', {
  query: () => ({ postId: postId.value })
})

Path parameters are resolved into the request URL, so each value gets a cache key of its own. With a key of your own, the key stays the same, and a changed path parameter or a getter passed as query sends no request – name its source in watch.

Caching ​

A response fetched during SSR reaches the browser in the Nuxt payload, and hydration reuses it instead of sending the request again. Beyond that, Nuxt's getCachedData decides when a call is answered from the payload – see Caching Strategies.

Examples ​

Demo Setup

These examples assume that you have set up an endpoint called jsonPlaceholder:

ts
export default defineNuxtConfig({
  modules: ['nuxt-api-party'],

  apiParty: {
    endpoints: {
      jsonPlaceholder: {
        url: 'https://jsonplaceholder.typicode.com'
      }
    }
  }
})

Basic ​

vue
<script setup lang="ts">
const { data, refresh, error, status, clear } = await useJsonPlaceholderData<{ title: string }>('posts/1')
</script>

<template>
  <div>
    <h1>{{ data?.title }}</h1>
    <button @click="refresh()">
      Refresh
    </button>
  </div>
</template>

Extended ​

vue
<script setup lang="ts">
interface Comment {
  id: number
  postId: number
  body: string
}

const postId = ref(1)

const { data, status, refresh, error } = await useJsonPlaceholderData('comments', {
  lazy: true,
  default: () => [] as Comment[],
  transform: (comments: Comment[]) => comments.filter(comment => comment.body.length > 0),
  query: computed(() => ({
    postId: postId.value
  })),
  headers: {
    'X-Foo': 'bar'
  }
})
</script>

<template>
  <div>
    <p v-for="comment in data" :key="comment.id">
      {{ comment.body }}
    </p>
    <button @click="refresh()">
      Refresh
    </button>
  </div>
</template>

Client Endpoints ​

A call to a client endpoint goes straight to the API – from the browser, and from the server during SSR – instead of through the server proxy. The endpoint sets this for all of its calls; no call option overrides it.

Released under the MIT License.