1
1
import {
2
+ ref ,
2
3
isRef ,
3
4
onBeforeMount ,
4
5
onServerPrefetch ,
@@ -49,7 +50,11 @@ function createGetCounter(counterObject: Record<string, any>, defaultKey = '') {
49
50
}
50
51
51
52
interface Fetch {
52
- ( context : ComponentInstance ) : void | Promise < void >
53
+ ( context : ComponentInstance ) : any | Promise < any >
54
+ }
55
+ interface UseFetchOptions {
56
+ expose ?: string ,
57
+ manual ?: boolean ,
53
58
}
54
59
55
60
const fetches = new WeakMap < ComponentInstance , Fetch [ ] > ( )
@@ -266,12 +271,54 @@ function getKey(vm: AugmentedComponentInstance) {
266
271
},
267
272
})
268
273
```
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
+ ```
269
300
*/
270
- export const useFetch = ( callback : Fetch ) => {
301
+ export const useFetch = ( callback : Fetch , options : UseFetchOptions ) => {
271
302
const vm = getCurrentInstance ( ) as AugmentedComponentInstance | undefined
272
303
if ( ! vm ) throw new Error ( 'This must be called within a setup function.' )
273
304
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
+ }
275
322
276
323
if ( typeof vm . $options . fetchOnServer === 'function' ) {
277
324
vm . _fetchOnServer = vm . $options . fetchOnServer . call ( vm ) !== false
@@ -293,6 +340,7 @@ export const useFetch = (callback: Fetch) => {
293
340
fetchState : vm ! . $fetchState ,
294
341
$fetch : vm ! . $fetch ,
295
342
$fetchState : vm ! . $fetchState ,
343
+ data : resultData ,
296
344
}
297
345
}
298
346
0 commit comments