Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
/nuxtPublic

feat!: simplifyuseAsyncData() handler signature#33629

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
OrbisK wants to merge1 commit intonuxt:main
base:main
Choose a base branch
Loading
fromOrbisK:feat/async-data-handler
Open
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletionsdocs/3.api/2.composables/use-async-data.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,7 +20,7 @@ Within your pages, components, and plugins you can use useAsyncData to get acces
<script setup lang="ts">
const { data, status, pending, error, refresh, clear } = await useAsyncData(
'mountains',
(_nuxtApp,{ signal }) => $fetch('https://api.nuxtjs.dev/mountains', { signal }),
({ signal }) => $fetch('https://api.nuxtjs.dev/mountains', { signal }),
)
</script>
```
Expand All@@ -42,7 +42,7 @@ The built-in `watch` option allows automatically rerunning the fetcher function
const page = ref(1)
const { data: posts } = await useAsyncData(
'posts',
(_nuxtApp,{ signal }) => $fetch('https://fakeApi.com/posts', {
({ signal }) => $fetch('https://fakeApi.com/posts', {
params: {
page: page.value,
},
Expand DownExpand Up@@ -78,7 +78,7 @@ You can make your `handler` function abortable by using the `signal` provided in
```ts
const { data, error } = await useAsyncData(
'users',
(_nuxtApp,{ signal }) => $fetch('/api/users', { signal }),
({ signal }) => $fetch('/api/users', { signal }),
)

refresh() // will actually cancel the $fetch request (if dedupe: cancel)
Expand All@@ -93,7 +93,7 @@ You can also pass an `AbortSignal` to the `refresh`/`execute` function to cancel
```ts
const { refresh } = await useAsyncData(
'users',
(_nuxtApp,{ signal }) => $fetch('/api/users', { signal }),
({ signal }) => $fetch('/api/users', { signal }),
)
let abortController: AbortController | undefined

Expand All@@ -112,7 +112,7 @@ If your `handler` function does not support abort signals, you can implement you
```ts
const { data, error } = await useAsyncData(
'users',
(_nuxtApp,{ signal }) => {
({ signal }) => {
return new Promise((resolve, reject) => {
signal?.addEventListener('abort', () => {
reject(new Error('Request aborted'))
Expand DownExpand Up@@ -194,12 +194,12 @@ The following options **can differ** without triggering warnings:

```ts
// ❌ This will trigger a development warning
const { data: users1 } = useAsyncData('users', (_nuxtApp,{ signal }) => $fetch('/api/users', { signal }), { deep: false })
const { data: users2 } = useAsyncData('users', (_nuxtApp,{ signal }) => $fetch('/api/users', { signal }), { deep: true })
const { data: users1 } = useAsyncData('users', ({ signal }) => $fetch('/api/users', { signal }), { deep: false })
const { data: users2 } = useAsyncData('users', ({ signal }) => $fetch('/api/users', { signal }), { deep: true })

// ✅ This is allowed
const { data: users1 } = useAsyncData('users', (_nuxtApp,{ signal }) => $fetch('/api/users', { signal }), { immediate: true })
const { data: users2 } = useAsyncData('users', (_nuxtApp,{ signal }) => $fetch('/api/users', { signal }), { immediate: false })
const { data: users1 } = useAsyncData('users', ({ signal }) => $fetch('/api/users', { signal }), { immediate: true })
const { data: users2 } = useAsyncData('users', ({ signal }) => $fetch('/api/users', { signal }), { immediate: false })
```

::tip
Expand DownExpand Up@@ -230,7 +230,7 @@ If you have not fetched data on the server (for example, with `server: false`),
## Type

```ts [Signature]
export type AsyncDataHandler<ResT> = (nuxtApp: NuxtApp, options:{ signal: AbortSignal }) => Promise<ResT>
export type AsyncDataHandler<ResT> = (context:{ signal: AbortSignal, nuxtApp: NuxtApp }) => Promise<ResT>

export function useAsyncData<DataT, DataE> (
handler: AsyncDataHandler<DataT>,
Expand Down
9 changes: 5 additions & 4 deletionspackages/nuxt/src/app/composables/asyncData.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@ export type AsyncDataRequestStatus = 'idle' | 'pending' | 'success' | 'error'

export type _Transform<Input = any, Output = any> = (input: Input) => Output | Promise<Output>

export type AsyncDataHandler<ResT> = (nuxtApp: NuxtApp, options:{ signal: AbortSignal }) => Promise<ResT>
export type AsyncDataHandler<ResT> = (context:{ signal: AbortSignal, nuxtApp: NuxtApp }) => Promise<ResT>

export type PickFrom<T, K extends Array<string>> = T extends Array<any>
? T
Expand DownExpand Up@@ -650,11 +650,12 @@ function createAsyncData<
// When prerendering, share payload data automatically between requests
const handler: AsyncDataHandler<ResT> = import.meta.client || !import.meta.prerender || !nuxtApp.ssrContext?._sharedPrerenderCache
? _handler
: (nuxtApp, options) => {
: (ctx) => {
const { nuxtApp } = ctx
const value = nuxtApp.ssrContext!._sharedPrerenderCache!.get(key)
if (value) { return value as Promise<ResT> }

const promise = Promise.resolve().then(() => nuxtApp.runWithContext(() => _handler(nuxtApp, options)))
const promise = Promise.resolve().then(() => nuxtApp.runWithContext(() => _handler(ctx)))

nuxtApp.ssrContext!._sharedPrerenderCache!.set(key, promise)
return promise
Expand DownExpand Up@@ -718,7 +719,7 @@ function createAsyncData<
reject(reason instanceof Error ? reason : new DOMException(String(reason ?? 'Aborted'), 'AbortError'))
}, { once: true })

return Promise.resolve(handler(nuxtApp,{ signal: mergedSignal })).then(resolve, reject)
return Promise.resolve(handler({ signal: mergedSignal, nuxtApp })).then(resolve, reject)
} catch (err) {
reject(err)
}
Expand Down
2 changes: 1 addition & 1 deletionpackages/nuxt/src/app/composables/fetch.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -147,7 +147,7 @@ export function useFetch<
watch([...watchSources || [], _fetchOptions], setImmediate, { flush: 'sync', once: true })
}

const asyncData = useAsyncData<_ResT, ErrorT, DataT, PickKeys, DefaultT>(watchSources === false ? key.value : key, (_,{ signal }) => {
const asyncData = useAsyncData<_ResT, ErrorT, DataT, PickKeys, DefaultT>(watchSources === false ? key.value : key, ({ signal }) => {
let _$fetch: H3Event$Fetch | $Fetch<unknown, NitroFetchRequest> = opts.$fetch || globalThis.$fetch

// Use fetch with request context and headers for server direct API calls
Expand Down
8 changes: 4 additions & 4 deletionstest/nuxt/use-async-data.test.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -955,7 +955,7 @@ describe('useAsyncData', () => {
it('should abort handler signal', async () => {
vi.useFakeTimers()
let _signal: AbortController['signal']
const promiseFn = vi.fn((_,{ signal }) => {
const promiseFn = vi.fn(({ signal }) => {
_signal = signal
return new Promise(resolve => setTimeout(() => resolve('index'), 1000))
})
Expand DownExpand Up@@ -1004,7 +1004,7 @@ describe('useAsyncData', () => {
const controller1 = new AbortController()

let receivedSignal: AbortSignal | undefined
const promiseFn = vi.fn((_,{ signal }) => {
const promiseFn = vi.fn(({ signal }) => {
receivedSignal = signal
return new Promise(resolve => setTimeout(() => resolve('test'), 1000))
})
Expand DownExpand Up@@ -1084,7 +1084,7 @@ describe('useAsyncData', () => {
it('should handle abort during dedupe:cancel', async () => {
vi.useFakeTimers()
let abortedCount = 0
const promiseFn = vi.fn((_,{ signal }) => {
const promiseFn = vi.fn(({ signal }) => {
signal.addEventListener('abort', () => abortedCount++)
return new Promise(resolve => setTimeout(() => resolve('test'), 1000))
})
Expand DownExpand Up@@ -1137,7 +1137,7 @@ describe('useAsyncData', () => {
vi.useFakeTimers()
let aborted = false

const promiseFn = vi.fn((_,{ signal }) => {
const promiseFn = vi.fn(({ signal }) => {
signal.addEventListener('abort', () => { aborted = true })
return new Promise(resolve => setTimeout(() => resolve('test'), 1000))
})
Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp