Skip to content

Commit

Permalink
fix(useFetch): broken callbacks when RequestInit and UseFetchOptions …
Browse files Browse the repository at this point in the history
…are both passed in (#2013)
  • Loading branch information
curtgrimes committed Jul 29, 2022
1 parent ffb24e7 commit 0f79145
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 2 deletions.
75 changes: 75 additions & 0 deletions packages/core/useFetch/index.test.ts
Expand Up @@ -181,6 +181,81 @@ describe('useFetch', () => {
})
})

test('should chain beforeFetch function when using a factory instance and the options object in useMyFetch', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
options: {
beforeFetch({ options }) {
options.headers = { ...options.headers, Global: 'foo' }
return { options }
},
},
})
useMyFetch(
'test',
{ method: 'GET' },
{
beforeFetch({ options }) {
options.headers = { ...options.headers, Local: 'foo' }
return { options }
},
})

await retry(() => {
expect(fetchSpyHeaders()).toMatchObject({ Global: 'foo', Local: 'foo' })
})
})

test('should chain afterFetch function when using a factory instance and the options object in useMyFetch', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
options: {
afterFetch(ctx) {
ctx.data.title = 'Global'
return ctx
},
},
})
const { data } = useMyFetch(
'test?json',
{ method: 'GET' },
{
afterFetch(ctx) {
ctx.data.title += ' Local'
return ctx
},
}).json()

await retry(() => {
expect(data.value).toEqual(expect.objectContaining({ title: 'Global Local' }))
})
})

test('should chain onFetchError function when using a factory instance and the options object in useMyFetch', async () => {
const useMyFetch = createFetch({
baseUrl: 'https://example.com',
options: {
onFetchError(ctx) {
ctx.data.title = 'Global'
return ctx
},
},
})
const { data } = useMyFetch(
'test?status=400&json',
{ method: 'GET' },
{
onFetchError(ctx) {
ctx.data.title += ' Local'
return ctx
},
}).json()

await retry(() => {
expect(data.value).toEqual(expect.objectContaining({ title: 'Global Local' }))
})
})

test('should run the beforeFetch function and add headers to the request', async () => {
useFetch('https://example.com', { headers: { 'Accept-Language': 'en-US' } }, {
beforeFetch({ options }) {
Expand Down
11 changes: 9 additions & 2 deletions packages/core/useFetch/index.ts
Expand Up @@ -260,8 +260,15 @@ export function createFetch(config: CreateFetchOptions = {}) {
}
}

if (args.length > 1 && isFetchOptions(args[1]))
options = { ...options, ...args[1] }
if (args.length > 1 && isFetchOptions(args[1])) {
options = {
...options,
...args[1],
beforeFetch: chainCallbacks(_options.beforeFetch, args[1].beforeFetch),
afterFetch: chainCallbacks(_options.afterFetch, args[1].afterFetch),
onFetchError: chainCallbacks(_options.onFetchError, args[1].onFetchError),
}
}

return useFetch(computedUrl, fetchOptions, options)
}
Expand Down

0 comments on commit 0f79145

Please sign in to comment.