11import {
2+ ref ,
23 isRef ,
34 onBeforeMount ,
45 onServerPrefetch ,
@@ -49,7 +50,11 @@ function createGetCounter(counterObject: Record<string, any>, defaultKey = '') {
4950}
5051
5152interface 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
5560const 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