diff --git a/docs/content/1.getting-started/3.composables.md b/docs/content/1.getting-started/3.composables.md index 9817f086..0eb20202 100644 --- a/docs/content/1.getting-started/3.composables.md +++ b/docs/content/1.getting-started/3.composables.md @@ -34,6 +34,28 @@ if (data.value?.ships) { } ``` +## useClientSideAsyncQuery + +Similar to `useAsyncQuery` this is a convenience wrapper around Nuxt's [useAsyncData](https://v3.nuxtjs.org/api/composables/use-async-data/) that allows you to easily query the Apollo client. Unlike `useAsyncQuery`, the request will only be made from the browser and not the server. + +`useClientSideAsyncQuery` is primarily used for querying data when a page or component is initially loaded but you only want to make the request from the browser. For example, if the responses from your GraphQL server are slow but you do not want to block the initial page render. + +```ts +const query = gql` +query getShips($limit: Int!) { + ships(limit: $limit) { + id + } +}` + +const { data } = await useClientSideAsyncQuery(query, { limit: 2 }) + +if (data.value?.ships) { + // log response + console.log(data.value.ships) +} +``` + ## useLazyAsyncQuery The `useLazyAsyncQuery` composable provides a wrapper around [`useAsyncQuery`](#useasyncquery) that lazily loads the specified query. diff --git a/src/module.ts b/src/module.ts index 51eb1f12..eb948c88 100644 --- a/src/module.ts +++ b/src/module.ts @@ -122,6 +122,7 @@ export default defineNuxtModule>({ ...[ 'useApollo', 'useAsyncQuery', + 'useClientSideAsyncQuery', 'useLazyAsyncQuery' ].map(n => ({ name: n, from: resolve('runtime/composables') })), ...(!options?.autoImports diff --git a/src/runtime/composables.ts b/src/runtime/composables.ts index 4d782794..b1f556c7 100644 --- a/src/runtime/composables.ts +++ b/src/runtime/composables.ts @@ -25,6 +25,15 @@ export function useAsyncQuery (...args: any) { return useAsyncData(key, fn) } +export function useClientSideAsyncQuery (opts: TAsyncQuery): AsyncData +export function useClientSideAsyncQuery (query: TQuery, clientId?: string): AsyncData +export function useClientSideAsyncQuery (query: TQuery, variables?: TVariables, clientId?: string, context?: DefaultContext): AsyncData + +export function useClientSideAsyncQuery (...args: any) { + const { key, fn } = prep(...args) + return useAsyncData(key, fn, { server: false }) +} + export function useLazyAsyncQuery (opts: TAsyncQuery): AsyncData export function useLazyAsyncQuery (query: TQuery, clientId?: string): AsyncData export function useLazyAsyncQuery (query: TQuery, variables?: TVariables, clientId?: string, context?: DefaultContext): AsyncData