Skip to content

Navigation Menu

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

Appearance settings

Commit 3ca0d92

Browse filesBrowse files
pkc918antfu
andauthored
fix(useFetch): partial overwrite when {combination: 'overwrite'} (#4430)
Co-authored-by: Anthony Fu <github@antfu.me>
1 parent e1a7ef3 commit 3ca0d92
Copy full SHA for 3ca0d92

File tree

2 files changed

+35
-1
lines changed
Filter options

2 files changed

+35
-1
lines changed

‎packages/core/useFetch/index.test.ts

Copy file name to clipboardExpand all lines: packages/core/useFetch/index.test.ts
+28
Original file line numberDiff line numberDiff line change
@@ -807,4 +807,32 @@ describe.skipIf(isBelowNode18)('useFetch', () => {
807807
expect(options?.execute).toBeDefined()
808808
})
809809
})
810+
811+
it('should partial overwrite when combination is overwrite', async () => {
812+
const useMyFetch = createFetch({
813+
baseUrl: 'https://example.com',
814+
combination: 'overwrite',
815+
options: {
816+
beforeFetch({ options }) {
817+
options.headers = { ...options.headers, before: 'Global' }
818+
return { options }
819+
},
820+
afterFetch(ctx) {
821+
ctx.data.after = 'Global'
822+
return ctx
823+
},
824+
},
825+
})
826+
827+
const { data } = useMyFetch('test', {
828+
beforeFetch({ options }) {
829+
options.headers = { ...options.headers, before: 'Local' }
830+
},
831+
}).json()
832+
833+
await vi.waitFor(() => {
834+
expect(fetchSpyHeaders()).toMatchObject({ before: 'Local' })
835+
expect(data.value).toEqual(expect.objectContaining({ after: 'Global' }))
836+
})
837+
})
810838
})

‎packages/core/useFetch/index.ts

Copy file name to clipboardExpand all lines: packages/core/useFetch/index.ts
+7-1
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,13 @@ function combineCallbacks<T = any>(combination: Combination, ...callbacks: (((ct
247247
if (combination === 'overwrite') {
248248
// use last callback
249249
return async (ctx: T) => {
250-
const callback = callbacks[callbacks.length - 1]
250+
let callback
251+
for (let i = callbacks.length - 1; i >= 0; i--) {
252+
if (callbacks[i] != null) {
253+
callback = callbacks[i]
254+
break
255+
}
256+
}
251257
if (callback)
252258
return { ...ctx, ...(await callback(ctx)) }
253259

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.