Skip to content
This repository was archived by the owner on Dec 5, 2024. It is now read-only.

Commit 742dbc9

Browse files
committed
feat: extend useFetch: add manual trigger option, add data to the return value.
1 parent 85238a3 commit 742dbc9

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

src/runtime/composables/fetch.ts

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
ref,
23
isRef,
34
onBeforeMount,
45
onServerPrefetch,
@@ -49,7 +50,11 @@ function createGetCounter(counterObject: Record<string, any>, defaultKey = '') {
4950
}
5051

5152
interface Fetch {
52-
(context: ComponentInstance): void | Promise<void>
53+
(context: ComponentInstance): any | Promise<any>
54+
}
55+
interface UseFetchOptions {
56+
expose?: string,
57+
manual?: boolean,
5358
}
5459

5560
const fetches = new WeakMap<ComponentInstance, Fetch[]>()
@@ -267,11 +272,27 @@ function getKey(vm: AugmentedComponentInstance) {
267272
})
268273
```
269274
*/
270-
export const useFetch = (callback: Fetch) => {
275+
export const useFetch = (callback: Fetch, options: UseFetchOptions) => {
271276
const vm = getCurrentInstance() as AugmentedComponentInstance | undefined
272277
if (!vm) throw new Error('This must be called within a setup function.')
273278

274-
registerCallback(vm, callback)
279+
const resultData = ref()
280+
let callbackProxy: Fetch = async function (this: any, ...args) {
281+
const result = await callback.apply(this, args)
282+
resultData.value = result
283+
return result
284+
}
285+
if (options.manual) {
286+
let callbackManually:Fetch = () => {
287+
callbackManually = callbackProxy
288+
}
289+
registerCallback(vm, callbackManually)
290+
} else {
291+
registerCallback(vm, callbackProxy)
292+
}
293+
if (options.expose) {
294+
vm[options.expose] = resultData
295+
}
275296

276297
if (typeof vm.$options.fetchOnServer === 'function') {
277298
vm._fetchOnServer = vm.$options.fetchOnServer.call(vm) !== false
@@ -293,6 +314,7 @@ export const useFetch = (callback: Fetch) => {
293314
fetchState: vm!.$fetchState,
294315
$fetch: vm!.$fetch,
295316
$fetchState: vm!.$fetchState,
317+
data: resultData,
296318
}
297319
}
298320

0 commit comments

Comments
 (0)