useSubscription
Reactive GraphQL subscription composable.
Subscriptions are client-only. They are not initialized on the server (SSR).
Quick start
ts
import { useSubscription } from '@vue3-apollo/core'
import { NEW_MESSAGES_SUB } from './gql' // your subscription document
const {
data,
error,
loading,
onData,
onError,
} = useSubscription(
NEW_MESSAGES_SUB,
() => ({
chatId: 'room-1',
}),
)
onData((payload) => {
console.log('New message:', payload)
})
onError((e) => {
console.error('Subscription error:', e)
})How it works
- Reactive variables: Pass a plain object, a
ref, or a getter; when variables change, the subscription restarts. - Lifecycle-aware: Starts automatically on mount if
enabledistrue; stops on scope dispose. - Client-only: Skips initialization during SSR; requires a WebSocket link in your Apollo client.
- Tracking: Integrates with internal tracking to reflect subscription activity.
API
Returns
data– the latest payload received (undefined until first event).loading–truewhile connecting / before first event.error– connection/transport/GraphQL error, if any.onData((data, context) => {})– subscribe to each incoming payload. Thecontextincludes the active Apollo client.tsonData((payload, context) => { console.log('New message:', payload) console.log('Client:', context.client) })onError((error, context) => {})– subscribe to errors, including connection or GraphQL issues. Thecontextcontains the Apollo client instance.tsonError((e, context) => { toast.error(e.message) console.error('Subscription error from client:', context.client) })start()– manually start or restart the subscription.stop()– stop and unsubscribe.
Options
enabled–boolean | Ref<boolean>(default:true). Whenfalse, the subscription won’t start until enabled orstart()is called.- Apollo subscribe options – you can pass standard Apollo
subscribeoptions (e.g.,context), exceptqueryandvariables, which are supplied by the composable. clientId– fromUseBaseOption, target a specific Apollo client instance if using multiple clients.