Skip to content

Commit 9302d4d

Browse files
committed
fix: hydration error, revert #1388, fix #1432
1 parent 3728928 commit 9302d4d

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

packages/vue-apollo-composable/src/useQuery.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ export function useQueryImpl<
196196
const query: Ref<ObservableQuery<TResult, TVariables> | null | undefined> = ref()
197197
let observer: ObservableSubscription | undefined
198198
let started = false
199+
let ignoreNextResult = false
199200

200201
/**
201202
* Starts watching the query
@@ -228,6 +229,20 @@ export function useQueryImpl<
228229

229230
startQuerySubscription()
230231

232+
// Make the cache data available to the component immediately
233+
// This prevents SSR hydration mismatches
234+
if (!isServer && (currentOptions.value?.fetchPolicy !== 'no-cache' || currentOptions.value.notifyOnNetworkStatusChange)) {
235+
const currentResult = query.value.getCurrentResult(false)
236+
237+
if (!currentResult.loading || currentResult.partial || currentOptions.value?.notifyOnNetworkStatusChange) {
238+
onNextResult(currentResult)
239+
ignoreNextResult = true
240+
} else if (currentResult.error) {
241+
onError(currentResult.error)
242+
ignoreNextResult = true
243+
}
244+
}
245+
231246
if (!isServer) {
232247
for (const item of subscribeToMoreItems) {
233248
addSubscribeToMore(item)
@@ -240,13 +255,19 @@ export function useQueryImpl<
240255
if (!query.value) return
241256

242257
// Create subscription
258+
ignoreNextResult = false
243259
observer = query.value.subscribe({
244260
next: onNextResult,
245261
error: onError,
246262
})
247263
}
248264

249265
function onNextResult (queryResult: ApolloQueryResult<TResult>) {
266+
if (ignoreNextResult) {
267+
ignoreNextResult = false
268+
return
269+
}
270+
250271
// Remove any previous error that may still be present from the last fetch (so result handlers
251272
// don't receive old errors that may not even be applicable anymore).
252273
error.value = null
@@ -273,6 +294,11 @@ export function useQueryImpl<
273294
}
274295

275296
function onError (queryError: unknown) {
297+
if (ignoreNextResult) {
298+
ignoreNextResult = false
299+
return
300+
}
301+
276302
// any error should already be an ApolloError, but we make sure
277303
const apolloError = toApolloError(queryError)
278304
const client = resolveClient(currentOptions.value?.clientId)

0 commit comments

Comments
 (0)