Skip to content

Commit

Permalink
feat(useFetch): cancel previous request on refetch (#2750)
Browse files Browse the repository at this point in the history
* fix(useFetch): cancel previous request

* chore(useFetch): improve test

---------

Co-authored-by: 丶远方 <pantengyang@cybstar.com>
  • Loading branch information
Alfred-Skyblue and 丶远方 committed Feb 11, 2023
1 parent 809fc98 commit cd9d6b4
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
34 changes: 33 additions & 1 deletion 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 '.'
Expand Down Expand Up @@ -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)
})
})
})
6 changes: 4 additions & 2 deletions packages/core/useFetch/index.ts
Expand Up @@ -357,8 +357,10 @@ export function useFetch<T>(url: MaybeComputedRef<string>, ...args: any[]): UseF
let timer: Stoppable | undefined

const abort = () => {
if (supportsAbort && controller)
if (supportsAbort && controller) {
controller.abort()
controller = undefined
}
}

const loading = (isLoading: boolean) => {
Expand All @@ -374,9 +376,9 @@ export function useFetch<T>(url: MaybeComputedRef<string>, ...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 = {
Expand Down

0 comments on commit cd9d6b4

Please sign in to comment.