Composables

Nuxt Apollo provides and Auto Imports key composables for seamless usage throughout your application.


useApollo

useApollo allows you to utilize Nuxt Apollo's authentication helpers as well as easily access the configured Apollo clients.

const { clients, getToken, onLogin, onLogout } = useApollo()

useAsyncQuery

This is a convenience wrapper around Nuxt's useAsyncData that allows you to easily query the Apollo client. The returned result is the extracted data property from the GraphQL query.

useAsyncQuery is primarily used for querying data when a page or component is initially loaded. Have a look at useQuery for fetching data upon user interaction.

const query = gql`query getShips($limit: Int!) {  ships(limit: $limit) {    id  }}`const { data } = await useAsyncQuery(query, { limit: 2 })if (data.value?.ships) {  // log response  console.log(data.value.ships)}

useLazyAsyncQuery

The useLazyAsyncQuery composable provides a wrapper around useAsyncQuery that lazily loads the specified query.

Unlike it's counterpart useAsyncQuery, useLazyAsyncQuery is non-blocking, hence the null state of your result must be manually handled.

const query = gql`  query currentUser {     whoAmI {       id     }  }`const { data } = await useAsyncQuery(query)

useQuery

This is the primary method of querying your GraphQL server, unlike useAsyncQuery which is best used for initially fetching data in SSR applications, useQuery can comfortably be used in any scenario.

const query = gql`  query getShips($limit: Int!) {    ships(limit: $limit) {      id    }  }`const variables = { limit: 5 }const { result } = useQuery(query, variables)

More Information on Vue Apollo's useQuery

useMutation

The useMutation composable allows you to modify server-side data

const query = gql`  mutation addUser ($input: UserInput!) {    addUser (input: $input) {      id    }  }`const variables = {  name: 'John Doe',  email: 'jd@example.com'}const { mutate } = useMutation(query, { variables })

More Information on Vue Apollo's useMutation

useSubscription

The useSubscription composable allows you to interface with WebSocket compliant GraphQL servers to listen for realtime updates.

Nuxt Apollo currently only supports subscriptions over WebSockets.
const query = gql`  subscription onMessageAdded($channelId: ID!) {    messageAdded(channelId: $channelId) {      id      text    }  }`const variables = { channelId: 'abc' }const { result } = useSubscription(query, variables)

More Information on Vue Apollo's useSubscription