Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

Commit

Permalink
feat(nuxt): refresh override for data fetching composables (#7864)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Oct 10, 2022
1 parent 829a550 commit 3856744
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 6 deletions.
6 changes: 6 additions & 0 deletions docs/content/1.getting-started/6.data-fetching.md
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/content/3.api/1.composables/use-async-data.md
Expand Up @@ -30,7 +30,7 @@ type AsyncDataOptions<DataT> = {
}

interface RefreshOptions {
_initial?: boolean
override?: boolean
}

type AsyncData<DataT, ErrorT> = {
Expand Down
2 changes: 1 addition & 1 deletion docs/content/3.api/1.composables/use-fetch.md
Expand Up @@ -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>
}
Expand Down
24 changes: 21 additions & 3 deletions packages/nuxt/src/app/composables/asyncData.ts
Expand Up @@ -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> {
Expand Down Expand Up @@ -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]) {
return 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))
Expand All @@ -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)
}
Expand All @@ -144,17 +156,23 @@ 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) {
nuxt.payload._errors[key] = true
}
delete nuxt._asyncDataPromises[key]
})
nuxt._asyncDataPromises[key] = promise
return nuxt._asyncDataPromises[key]
}

Expand Down
6 changes: 5 additions & 1 deletion packages/nuxt/src/app/composables/fetch.ts
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions test/basic.test.ts
Expand Up @@ -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')
})
Expand Down
36 changes: 36 additions & 0 deletions test/fixtures/basic/pages/useAsyncData/override.vue
@@ -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>

0 comments on commit 3856744

Please sign in to comment.