custom uselazyfetch
codes below are my custom usefetch, how to make a uselazyfetch?
import type { UseFetchOptions } from '#app'
export const useAPI = <T>(
url: string | (() => string),
options?: UseFetchOptions<T>,
) => {
return useFetch(url, {
...options,
$fetch: useNuxtApp().$api as typeof $fetch,
})
}
2 Replies
Hi @Zhaolin Lau. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
To create a custom
useLazyFetch composable similar to your custom useAPI (which wraps useFetch), you just need to set the lazy: true option when calling useFetch. This is exactly how Nuxt's built-in useLazyFetch works—it simply wraps useFetch with the lazy option enabled. Here’s how you can do it:
This will give you the same behavior as useLazyFetch, but with your custom $api instance. You can use it in your components just like your useAPI composable, and it will not block navigation while fetching data—remember to handle the loading state in your template, as data may not be immediately available on navigation see official docs see custom useFetch recipe.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@520675622830342144> Kapa.ai is still learning and improving, please let me know how I did by reacting below.