NuxtN
Nuxt2mo ago
15 replies
t.f.e

Custom useAuthFetch - Not getting types as useFetch

import type { UseFetchOptions } from "nuxt/app";
import { useUserStore } from "@/store/user";

export async function useAPI<T>(
  url: string | (() => string),
  options?: UseFetchOptions<T>
) {
  const userStore = useUserStore();
  const accessToken = await userStore.getAccessToken();
  
  const fetchOptions = {
    ...options,
    headers: {
      ...(options?.headers || {}),
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json",
    },
  }

  return useFetch(url, {
    ...fetchOptions,
    $fetch: useNuxtApp().$api as typeof $fetch,
  });
}


Using this composable to inject the access token i do not get the type returned from the api on it. See the images, image one is hovering the "useAPI" custom one. The second is the useFetch.

How can i make my custom useAPI have the same typing as useFetch so it changed depending on the url. also the autocomplete does not work on my custom usefetch whereas the useFetch it autocompletes all the API's. (image 3)
image.png
image.png
image.png
Was this page helpful?