Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useFetch): cancel previous request #2750

Merged
merged 2 commits into from
Feb 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 33 additions & 1 deletion packages/core/useFetch/index.test.ts
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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