From cd9d6b48687df925be15d77d58b2da4c6c8bd918 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=B6=E8=BF=9C=E6=96=B9?= Date: Sat, 11 Feb 2023 13:33:11 +0800 Subject: [PATCH] feat(useFetch): cancel previous request on refetch (#2750) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(useFetch): cancel previous request * chore(useFetch): improve test --------- Co-authored-by: 丶远方 --- packages/core/useFetch/index.test.ts | 34 +++++++++++++++++++++++++++- packages/core/useFetch/index.ts | 6 +++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/packages/core/useFetch/index.test.ts b/packages/core/useFetch/index.test.ts index 6c16838b29b..e7efc1c0335 100644 --- a/packages/core/useFetch/index.test.ts +++ b/packages/core/useFetch/index.test.ts @@ -1,5 +1,5 @@ import { until } from '@vueuse/shared' -import { ref } from 'vue-demi' +import { nextTick, ref } from 'vue-demi' import type { SpyInstance } from 'vitest' import { retry } from '../../.test' import { createFetch, useFetch } from '.' @@ -658,4 +658,36 @@ describe('useFetch', () => { expect(data.value).toEqual(jsonMessage) expect(fetchSpy).toBeCalledTimes(1) }) + + test('should abort previous request', async () => { + const { onFetchResponse, execute } = useFetch('https://example.com', { immediate: false }) + + onFetchResponse(onFetchResponseSpy) + + execute() + execute() + execute() + execute() + + await retry(() => { + expect(onFetchResponseSpy).toBeCalledTimes(1) + }) + }) + + it('should listen url ref change abort previous request', async () => { + const url = ref('https://example.com') + const { onFetchResponse } = useFetch(url, { refetch: true, immediate: false }) + + onFetchResponse(onFetchResponseSpy) + + url.value = 'https://example.com?t=1' + await nextTick() + url.value = 'https://example.com?t=2' + await nextTick() + url.value = 'https://example.com?t=3' + + await retry(() => { + expect(onFetchResponseSpy).toBeCalledTimes(1) + }) + }) }) diff --git a/packages/core/useFetch/index.ts b/packages/core/useFetch/index.ts index c8160701ddd..2084d33245b 100644 --- a/packages/core/useFetch/index.ts +++ b/packages/core/useFetch/index.ts @@ -357,8 +357,10 @@ export function useFetch(url: MaybeComputedRef, ...args: any[]): UseF let timer: Stoppable | undefined const abort = () => { - if (supportsAbort && controller) + if (supportsAbort && controller) { controller.abort() + controller = undefined + } } const loading = (isLoading: boolean) => { @@ -374,9 +376,9 @@ export function useFetch(url: MaybeComputedRef, ...args: any[]): UseF error.value = null statusCode.value = null aborted.value = false - controller = undefined if (supportsAbort) { + abort() controller = new AbortController() controller.signal.onabort = () => aborted.value = true fetchOptions = {