How to create a copy of useFetch inside a custom hook?
P粉928591383
P粉928591383 2023-08-28 15:24:54
0
1
360
<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粉928591383
P粉928591383

reply all(1)
P粉032900484

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,
  }
)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!