Stanislav Nasonov
Stanislav Nasonov

Reputation: 141

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

I'm trying to create a hook for multiple use, but I get the behavior not the one that I expect

/composables/fetch.ts

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);
  });

enter image description here

Only the first request is triggered

const { data: response } = await useFetchWithErrorHandler(`page-1`, {
    pick: ['data'],
});

const { data: response } = await useFetchWithErrorHandler(`page-2`, {
    pick: ['data'],
});

Upvotes: 0

Views: 660

Answers (1)

some-user
some-user

Reputation: 4934

useFetch uses caching to avoid multiple identical requests.

You can disable caching if you set initialCache: false in the options, e.g.

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

Upvotes: 1

Related Questions