Skip to content

Commit

Permalink
fix(useFetch): fix incorrect chainCallbacks behavior (#2231)
Browse files Browse the repository at this point in the history
  • Loading branch information
GODLiangCY committed Oct 5, 2022
1 parent 554a3cf commit 457509a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
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

0 comments on commit 457509a

Please sign in to comment.