NuxtN
Nuxt6mo ago
13 replies
Tilko

custom useFetch composable return typing response

This is my useCustomFetch wrapper.
import type { UseFetchOptions } from 'nuxt/app'

export function useCustomFetch<T>(
  url: Parameters<typeof $fetch>[0],
  options: UseFetchOptions<T> = {},
) {
  return useLazyFetch(url, {
    credentials: 'include',
    ...options,
    onResponseError(context) {
      if (context.response.status === 401) {
        navigateTo('/login')
      }
    },
  })
}


in server/api/public/test.get.ts I created a simple json response.
export default defineEventHandler(event => {
  return {
    a: 'a',
    b: 'b',
    nested: {
      c: 'c',
      d: 'd',
    },
  }
})


If I use normal useFetch it already knows the response from the endpoint and it apply types and in majority of cases (atleast in theory) I won't even need to write types for the reponses
image.png
Was this page helpful?