NuxtN
Nuxt2y ago
17 replies
Mike

Typing a custom `useFetch` to include null

I've created a custom implementation to handle caching and error handling. I've followed these docs: https://nuxt.com/docs/guide/recipes/custom-usefetch#custom-usefetchuseasyncdata

However unlike a the native useFetch, the type of data doesn't include null
I've attached a screenshot where you can see the types.
The code is this:
import type { UseFetchOptions } from "nuxt/app"

export function useAPI<T>(
  url: string | (() => string),
  options?: Omit<UseFetchOptions<T>, "default"> & { default: () => T | Ref<T> },
) {
  return useFetch(url, {
    ...options,
    $fetch: useNuxtApp().$api,
  })
}

type MyReturnType = { data: string }
const { data: a } = await useFetch<MyReturnType>("/api/url")
//            ^?
const { data: b } = await useAPI<MyReturnType>("/api/url")
//            ^?

I've also tried typing my custom fetch return type with ReturnType<typeof useFetch>, with no results.
How can I type my custom fetch to make the data type be Ref<T | null>?
image.png
Nuxt
How to create a custom fetcher for calling your external API in Nuxt 3.
Custom useFetch in Nuxt · Recipes
Was this page helpful?