Home  >  Q&A  >  body text

How to create a copy of useFetch inside a custom hook?

<p>I'm trying to create a hook that can be used multiple times, but the behavior I'm getting is not what I expect</p> <p>/composables/fetch.ts</p> <pre class="brush:js;toolbar:false;">export const useFetchWithErrorHandler = async (url: string, options?: FetchOptions) => { const route = useRoute(); const { API_BASE_URL, API_PREFIX } = useRuntimeConfig(); console.log(url, options); return new Promise(async (resolve, reject) => { const response = await useFetch(API_PREFIX url, { ...options, baseURL: API_BASE_URL, initialCache: false, async onResponse({ request, response, options }) { console.log('[fetch response]', response); }, async onResponseError({ request, response, options }) { console.log('[fetch response error]'); }, }); resolve(response); }); </pre> <p>Only triggers the first request</p> <pre class="brush:js;toolbar:false;">const { data: response } = await useFetchWithErrorHandler(`page-1`, { pick: ['data'], }); const { data: response } = await useFetchWithErrorHandler(`page-2`, { pick: ['data'], }); </pre></p>
P粉928591383P粉928591383417 days ago358

reply all(1)I'll reply

  • P粉032900484

    P粉0329004842023-08-29 09:48:02

    useFetch Use caching to avoid multiple identical requests.

    You can disable caching if you set initialCache: false in the options, for example

    useFetch(API_PREFIX + url, {
        ...options,
        initialCache: false,
      }
    )
    

    reply
    0
  • Cancelreply