mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-22 05:35:13 +00:00
feat(nuxt): refresh override for data fetching composables (#7864)
This commit is contained in:
parent
829a550580
commit
385674494d
@ -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.
|
||||
|
@ -30,7 +30,7 @@ type AsyncDataOptions<DataT> = {
|
||||
}
|
||||
|
||||
interface RefreshOptions {
|
||||
_initial?: boolean
|
||||
override?: boolean
|
||||
}
|
||||
|
||||
type AsyncData<DataT, ErrorT> = {
|
||||
|
@ -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>
|
||||
}
|
||||
|
@ -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]
|
||||
}
|
||||
|
||||
|
@ -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
|
||||
|
@ -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')
|
||||
})
|
||||
|
36
test/fixtures/basic/pages/useAsyncData/override.vue
vendored
Normal file
36
test/fixtures/basic/pages/useAsyncData/override.vue
vendored
Normal 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>
|
Loading…
Reference in New Issue
Block a user