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

Commit cd5056d

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

File tree

1 file changed

+51
-3
lines changed

1 file changed

+51
-3
lines changed

src/runtime/composables/fetch.ts

+51-3
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[]>()
@@ -266,12 +271,54 @@ function getKey(vm: AugmentedComponentInstance) {
266271
},
267272
})
268273
```
274+
275+
```ts
276+
import { defineComponent, ref, useFetch } from '@nuxtjs/composition-api'
277+
import axios from 'axios'
278+
279+
export default defineComponent({
280+
setup() {
281+
const { fetch, fetchState, data } = useFetch(
282+
async () => {
283+
// The return value will be set to
284+
return await axios.get('https://myapi.com/name')
285+
},
286+
{
287+
manual: true, // Disable auto fetch unless `fetch()` is called manually
288+
expose: 'name', // The name exposed to the template by which can access the hook's return value
289+
},
290+
)
291+
292+
// Manually trigger a refetch
293+
fetch()
294+
295+
// Access the returned value of fetch hook
296+
data.value
297+
},
298+
})
299+
```
269300
*/
270-
export const useFetch = (callback: Fetch) => {
301+
export const useFetch = (callback: Fetch, options: UseFetchOptions) => {
271302
const vm = getCurrentInstance() as AugmentedComponentInstance | undefined
272303
if (!vm) throw new Error('This must be called within a setup function.')
273304

274-
registerCallback(vm, callback)
305+
const resultData = ref()
306+
let callbackProxy: Fetch = async function (this: any, ...args) {
307+
const result = await callback.apply(this, args)
308+
resultData.value = result
309+
return result
310+
}
311+
if (options.manual) {
312+
let callbackManually:Fetch = () => {
313+
callbackManually = callbackProxy
314+
}
315+
registerCallback(vm, callbackManually)
316+
} else {
317+
registerCallback(vm, callbackProxy)
318+
}
319+
if (options.expose) {
320+
vm[options.expose] = resultData
321+
}
275322

276323
if (typeof vm.$options.fetchOnServer === 'function') {
277324
vm._fetchOnServer = vm.$options.fetchOnServer.call(vm) !== false
@@ -293,6 +340,7 @@ export const useFetch = (callback: Fetch) => {
293340
fetchState: vm!.$fetchState,
294341
$fetch: vm!.$fetch,
295342
$fetchState: vm!.$fetchState,
343+
data: resultData,
296344
}
297345
}
298346

0 commit comments

Comments
 (0)