From fa139420528753b8f7f791c799645886fe17a87c Mon Sep 17 00:00:00 2001 From: Alex Liu Date: Mon, 16 Dec 2024 22:00:51 +0800 Subject: [PATCH] fix: ensure `queryKey` match the current value of ref used inside --- packages/vue-query/src/useQueries.ts | 66 +++++++++++++++------------- 1 file changed, 35 insertions(+), 31 deletions(-) diff --git a/packages/vue-query/src/useQueries.ts b/packages/vue-query/src/useQueries.ts index 371fdcc4db..ee9278997f 100644 --- a/packages/vue-query/src/useQueries.ts +++ b/packages/vue-query/src/useQueries.ts @@ -297,11 +297,31 @@ export function useQueries< defaultedQueries.value, options as QueriesObserverOptions, ) - const [, getCombinedResult] = observer.getOptimisticResult( - defaultedQueries.value, - (options as QueriesObserverOptions).combine, - ) - const state = shallowRef(getCombinedResult()) + + const getOptimisticResult = () => { + const [results, getCombinedResult] = observer.getOptimisticResult( + defaultedQueries.value, + (options as QueriesObserverOptions).combine, + ) + + return getCombinedResult( + results.map((result, index) => { + return { + ...result, + refetch: async (...args: Array) => { + const [{ [index]: query }] = observer.getOptimisticResult( + defaultedQueries.value, + (options as QueriesObserverOptions).combine, + ) + + return query!.refetch(...args) + }, + } + }), + ) + } + + const state = shallowRef(getOptimisticResult()) let unsubscribe = () => { // noop @@ -313,38 +333,22 @@ export function useQueries< if (!isRestoring) { unsubscribe() unsubscribe = observer.subscribe(() => { - const [, getCombinedResultRestoring] = observer.getOptimisticResult( - defaultedQueries.value, - (options as QueriesObserverOptions).combine, - ) - state.value = getCombinedResultRestoring() + state.value = getOptimisticResult() }) - // Subscription would not fire for persisted results - const [, getCombinedResultPersisted] = observer.getOptimisticResult( - defaultedQueries.value, - (options as QueriesObserverOptions).combine, - ) - state.value = getCombinedResultPersisted() + + state.value = getOptimisticResult() } }, { immediate: true }, ) - watch( - defaultedQueries, - () => { - observer.setQueries( - defaultedQueries.value, - options as QueriesObserverOptions, - ) - const [, getCombinedResultPersisted] = observer.getOptimisticResult( - defaultedQueries.value, - (options as QueriesObserverOptions).combine, - ) - state.value = getCombinedResultPersisted() - }, - { flush: 'sync' }, - ) + watch(defaultedQueries, (queriesValue) => { + observer.setQueries( + queriesValue, + options as QueriesObserverOptions, + ) + state.value = getOptimisticResult() + }) onScopeDispose(() => { unsubscribe()