Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/two-heads-prove.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@vue3-apollo/core": patch
"@vue3-apollo/nuxt": patch
---

fix(core): support reactive GraphQL documents in `useSubscription`
24 changes: 15 additions & 9 deletions packages/core/src/composables/useSubscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import type { DocumentNode } from 'graphql'
import type { MaybeRefOrGetter, Ref } from 'vue'

import { createEventHook, syncRef } from '@vueuse/core'
import { getCurrentScope, isReadonly, isRef, onScopeDispose, ref, shallowRef, toRef, toValue, watch } from 'vue'
import { computed, getCurrentScope, isReadonly, isRef, onScopeDispose, ref, shallowRef, toRef, toValue, watch } from 'vue'

import type { HookContext, UseBaseOption } from '../utils/type'

Expand Down Expand Up @@ -45,7 +45,7 @@ export function useSubscription<
TData = unknown,
TVariables extends OperationVariables = OperationVariables
>(
document: DocumentNode | TypedDocumentNode<TData, TVariables>,
document: MaybeRefOrGetter<DocumentNode | TypedDocumentNode<TData, TVariables>>,
variables?: MaybeRefOrGetter<TVariables>,
options?: UseSubscriptionOptions<TData, TVariables>
) {
Expand All @@ -70,6 +70,8 @@ export function useSubscription<
})
}

const reactiveDocument = computed(() => toValue(document))

useApolloTracking({
state: loading,
type: 'subscriptions'
Expand Down Expand Up @@ -127,14 +129,21 @@ export function useSubscription<
}

subscription.value = client.subscribe<TData, TVariables>({
query: document,
query: reactiveDocument.value,
variables: toValue(reactiveVariables),
...options
})

startObserver()
}

const restart = () => {
if (enabled.value) {
stop()
start()
}
}

// Subscriptions only work on the client-side (require WebSocket)
// Skip initialization on server during SSR
if (!isServer()) {
Expand All @@ -149,16 +158,13 @@ export function useSubscription<
}
})

watch(reactiveVariables, () => {
if (enabled.value) {
stop()
start()
}
}, {
watch(reactiveVariables, restart, {
deep: true,
flush: 'post'
})

watch(reactiveDocument, restart)

if (getCurrentScope()) {
onScopeDispose(() => {
stop()
Expand Down
Loading