Skip to content

Commit 296a2ab

Browse files
authored
Merge pull request #31 from guendev/fix/27-2
fix(core): support reactive GraphQL documents in `useSubscription`
2 parents d5f4124 + e6dc841 commit 296a2ab

File tree

2 files changed

+21
-9
lines changed

2 files changed

+21
-9
lines changed

.changeset/two-heads-prove.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@vue3-apollo/core": patch
3+
"@vue3-apollo/nuxt": patch
4+
---
5+
6+
fix(core): support reactive GraphQL documents in `useSubscription`

packages/core/src/composables/useSubscription.ts

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import type { DocumentNode } from 'graphql'
1010
import type { MaybeRefOrGetter, Ref } from 'vue'
1111

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

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

@@ -45,7 +45,7 @@ export function useSubscription<
4545
TData = unknown,
4646
TVariables extends OperationVariables = OperationVariables
4747
>(
48-
document: DocumentNode | TypedDocumentNode<TData, TVariables>,
48+
document: MaybeRefOrGetter<DocumentNode | TypedDocumentNode<TData, TVariables>>,
4949
variables?: MaybeRefOrGetter<TVariables>,
5050
options?: UseSubscriptionOptions<TData, TVariables>
5151
) {
@@ -70,6 +70,8 @@ export function useSubscription<
7070
})
7171
}
7272

73+
const reactiveDocument = computed(() => toValue(document))
74+
7375
useApolloTracking({
7476
state: loading,
7577
type: 'subscriptions'
@@ -127,14 +129,21 @@ export function useSubscription<
127129
}
128130

129131
subscription.value = client.subscribe<TData, TVariables>({
130-
query: document,
132+
query: reactiveDocument.value,
131133
variables: toValue(reactiveVariables),
132134
...options
133135
})
134136

135137
startObserver()
136138
}
137139

140+
const restart = () => {
141+
if (enabled.value) {
142+
stop()
143+
start()
144+
}
145+
}
146+
138147
// Subscriptions only work on the client-side (require WebSocket)
139148
// Skip initialization on server during SSR
140149
if (!isServer()) {
@@ -149,16 +158,13 @@ export function useSubscription<
149158
}
150159
})
151160

152-
watch(reactiveVariables, () => {
153-
if (enabled.value) {
154-
stop()
155-
start()
156-
}
157-
}, {
161+
watch(reactiveVariables, restart, {
158162
deep: true,
159163
flush: 'post'
160164
})
161165

166+
watch(reactiveDocument, restart)
167+
162168
if (getCurrentScope()) {
163169
onScopeDispose(() => {
164170
stop()

0 commit comments

Comments
 (0)