victorgarciaesgi / nuxt-typed-router

🚦Provide autocompletion and typecheck to Nuxt router
https://nuxt-typed-router.vercel.app
MIT License
361 stars 12 forks source link

Losing type inference when using custom fetch #126

Closed Amar-Gill closed 12 months ago

Amar-Gill commented 12 months ago

Describe the bug The autocompletion provided for endpoints when using useFetch is missing when using a custom useFetch, following the example given in Nuxt Docs.

Expected behavior Autocompleted endpoints when typing the url for the custom fetch composable, just as for the base composable.

Screenshots Custom fetch, no autocomplete: Screenshot 2023-11-19 at 10 14 09 AM

Environnement infos

Your pages folder structure

pages
├── index.vue
├── login.vue
├── profile.vue
├── proj
│   ├── [project-id]
│   │   ├── reports.vue
│   │   └── summary.vue
│   └── new.vue
└── report
    └── [report-id].vue

4 directories, 7 files

Your nuxt.config.ts

  modules: ['@nuxt/ui', 'nuxt-prepare', 'nuxt-typed-router', '@vueuse/nuxt'],

My Specific Custom useFetch Implementation (based on official nuxt.com example)

import type { UseFetchOptions } from 'nuxt/app';
import { defu } from 'defu';

export function useProtectedFetch<T>(
  url: string | (() => string),
  options: UseFetchOptions<T> = {}
) {
  const auth = useAuthState();

  const defaults: UseFetchOptions<T> = {
    headers: {
      ...options?.headers,
      Authorization: `Bearer ${auth.value?.accessToken}`,
    },

    async onResponseError(_ctx) {
      const status = _ctx.response.status;

      if (status === 401) {
        await navigateTo('/login');
      }
    },
  };

  // for nice deep defaults, please use unjs/defu
  const params = defu(options, defaults);

  return useFetch(url, params);
}
Amar-Gill commented 12 months ago

Um apologies this is not in the scope of typed-router 😅