feat(nuxt): refresh override for data fetching composables (#7864)

This commit is contained in:
Daniel Roe 2022-10-10 11:33:16 +01:00 committed by GitHub
parent 829a550580
commit 385674494d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 74 additions and 6 deletions

View File

@ -152,6 +152,12 @@ function next() {
The key to making this work is to call the `refresh()` method returned from the `useFetch()` composable when a query parameter has changed.
By default, `refresh()` will not make a new request if one is already pending. You can override any pending requests with the override option. Previous requests will not be cancelled, but their result will not update the data or pending state - and any previously awaited promises will not resolve until this new request resolves.
```js
refresh({ override: true })
```
### `refreshNuxtData`
Invalidate the cache of `useAsyncData`, `useLazyAsyncData`, `useFetch` and `useLazyFetch` and trigger the refetch.

View File

@ -30,7 +30,7 @@ type AsyncDataOptions<DataT> = {
}
interface RefreshOptions {
_initial?: boolean
override?: boolean
}
type AsyncData<DataT, ErrorT> = {

View File

@ -32,7 +32,7 @@ type UseFetchOptions = {
type AsyncData<DataT> = {
data: Ref<DataT>
pending: Ref<boolean>
refresh: () => Promise<void>
refresh: (opts?: { override?: boolean }) => Promise<void>
execute: () => Promise<void>
error: Ref<Error | boolean>
}

View File

@ -34,6 +34,12 @@ export interface AsyncDataOptions<
export interface AsyncDataExecuteOptions {
_initial?: boolean
/**
* Force a refresh, even if there is already a pending request. Previous requests will
* not be cancelled, but their result will not affect the data/pending state - and any
* previously awaited promises will not resolve until this new request resolves.
*/
override?: boolean
}
export interface _AsyncData<DataT, ErrorT> {
@ -115,17 +121,20 @@ export function useAsyncData<
const asyncData = { ...nuxt._asyncData[key] } as AsyncData<DataT, DataE>
asyncData.refresh = asyncData.execute = (opts = {}) => {
// Avoid fetching same key more than once at a time
if (nuxt._asyncDataPromises[key]) {
if (!opts.override) {
// Avoid fetching same key more than once at a time
return nuxt._asyncDataPromises[key]
}
(nuxt._asyncDataPromises[key] as any).cancelled = true
}
// Avoid fetching same key that is already fetched
if (opts._initial && useInitialCache()) {
return nuxt.payload.data[key]
}
asyncData.pending.value = true
// TODO: Cancel previous promise
nuxt._asyncDataPromises[key] = new Promise<DataT>(
const promise = new Promise<DataT>(
(resolve, reject) => {
try {
resolve(handler(nuxt))
@ -134,6 +143,9 @@ export function useAsyncData<
}
})
.then((result) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
if (options.transform) {
result = options.transform(result)
}
@ -144,10 +156,15 @@ export function useAsyncData<
asyncData.error.value = null
})
.catch((error: any) => {
// If this request is cancelled, resolve to the latest request.
if ((promise as any).cancelled) { return nuxt._asyncDataPromises[key] }
asyncData.error.value = error
asyncData.data.value = unref(options.default?.() ?? null)
})
.finally(() => {
if ((promise as any).cancelled) { return }
asyncData.pending.value = false
nuxt.payload.data[key] = asyncData.data.value
if (asyncData.error.value) {
@ -155,6 +172,7 @@ export function useAsyncData<
}
delete nuxt._asyncDataPromises[key]
})
nuxt._asyncDataPromises[key] = promise
return nuxt._asyncDataPromises[key]
}

View File

@ -86,8 +86,12 @@ export function useFetch<
]
}
let controller: AbortController
const asyncData = useAsyncData<_ResT, ErrorT, Transform, PickKeys>(key, () => {
return $fetch(_request.value, _fetchOptions) as Promise<_ResT>
controller?.abort?.()
controller = typeof AbortController !== 'undefined' ? new AbortController() : {} as AbortController
return $fetch(_request.value, { signal: controller.signal, ..._fetchOptions }) as Promise<_ResT>
}, _asyncDataOptions)
return asyncData

View File

@ -824,6 +824,10 @@ describe.skipIf(isWindows)('useAsyncData', () => {
await $fetch('/useAsyncData/refresh')
})
it('requests can be cancelled/overridden', async () => {
await expectNoClientErrors('/useAsyncData/override')
})
it('two requests made at once resolve and sync', async () => {
await expectNoClientErrors('/useAsyncData/promise-all')
})

View File

@ -0,0 +1,36 @@
<template>
<div>
Override
{{ data }}
</div>
</template>
<script setup lang="ts">
let count = 0
let timeout = 0
const { data, refresh } = await useAsyncData(() => process.server ? Promise.resolve(1) : new Promise(resolve => setTimeout(() => resolve(++count), timeout)))
if (count || data.value !== 1) {
throw new Error('Data should be unset')
}
timeout = 100
const p = refresh()
if (process.client && (count !== 0 || data.value !== 1)) {
throw new Error('count should start at 0')
}
timeout = 0
await refresh({ override: true })
if (process.client && (count !== 1 || data.value !== 1)) {
throw new Error('override should execute')
}
await p
if (process.client && (count !== 2 || data.value !== 1)) {
throw new Error('cancelled promise should not affect data')
}
</script>