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

fix(useFetch): fix incorrect chainCallbacks behavior #2231

Merged
merged 5 commits into from Oct 5, 2022
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
42 changes: 42 additions & 0 deletions packages/core/useFetch/index.test.ts
Expand Up @@ -337,6 +337,48 @@ describe('useFetch', () => {
})
})

test('async chained beforeFetch and afterFetch should be executed in order', async () => {
const sleep = (delay: number) => new Promise(resolve => setTimeout(resolve, delay))

const useMyFetch = createFetch({
baseUrl: 'https://example.com',
options: {
async beforeFetch({ options }) {
await sleep(50)
options.headers = { ...options.headers, title: 'Hunter X Hunter' }
return { options }
},
async afterFetch(ctx) {
await sleep(50)
ctx.data.message = 'Hunter X Hunter'
return ctx
},
},
})

const { data } = await useMyFetch(
'test?json',
{ method: 'GET' },
{
async beforeFetch({ options }) {
await Promise.resolve()
options.headers = { ...options.headers, title: 'Hello, VueUse' }
return { options }
},
async afterFetch(ctx) {
await Promise.resolve()
ctx.data.message = 'Hello, VueUse'
return ctx
},
},
).json()

await retry(() => {
expect(fetchSpyHeaders()).toMatchObject({ title: 'Hello, VueUse' })
expect(data.value).toEqual(expect.objectContaining({ message: 'Hello, VueUse' }))
})
})

test('should run the onFetchError function', async () => {
const { data, statusCode } = useFetch('https://example.com?status=400&json', {
onFetchError(ctx) {
Expand Down
6 changes: 3 additions & 3 deletions packages/core/useFetch/index.ts
Expand Up @@ -215,11 +215,11 @@ function headersToObject(headers: HeadersInit | undefined) {
}

function chainCallbacks<T = any>(...callbacks: (((ctx: T) => void | Partial<T> | Promise<void | Partial<T>>) | undefined)[]) {
return (ctx: T) => {
callbacks.forEach(async (callback) => {
return async (ctx: T) => {
await callbacks.reduce((prevCallback, callback) => prevCallback.then(async () => {
if (callback)
ctx = { ...ctx, ...(await callback(ctx)) }
})
}), Promise.resolve())
return ctx
}
}
Expand Down