Skip to content

Commit

Permalink
feat: extend useFetch: add manual trigger option, add data to the…
Browse files Browse the repository at this point in the history
… return value.
  • Loading branch information
caikan committed Jun 17, 2021
1 parent 85238a3 commit 742dbc9
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions src/runtime/composables/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
ref,
isRef,
onBeforeMount,
onServerPrefetch,
Expand Down Expand Up @@ -49,7 +50,11 @@ function createGetCounter(counterObject: Record<string, any>, defaultKey = '') {
}

interface Fetch {
(context: ComponentInstance): void | Promise<void>
(context: ComponentInstance): any | Promise<any>
}
interface UseFetchOptions {
expose?: string,
manual?: boolean,
}

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

registerCallback(vm, callback)
const resultData = ref()
let callbackProxy: Fetch = async function (this: any, ...args) {
const result = await callback.apply(this, args)
resultData.value = result
return result
}
if (options.manual) {
let callbackManually:Fetch = () => {
callbackManually = callbackProxy
}
registerCallback(vm, callbackManually)
} else {
registerCallback(vm, callbackProxy)
}
if (options.expose) {
vm[options.expose] = resultData
}

if (typeof vm.$options.fetchOnServer === 'function') {
vm._fetchOnServer = vm.$options.fetchOnServer.call(vm) !== false
Expand All @@ -293,6 +314,7 @@ export const useFetch = (callback: Fetch) => {
fetchState: vm!.$fetchState,
$fetch: vm!.$fetch,
$fetchState: vm!.$fetchState,
data: resultData,
}
}

Expand Down

0 comments on commit 742dbc9

Please sign in to comment.